Skip to main content
Improved wording.
Source Link
Pang
  • 10.2k
  • 146
  • 87
  • 126

I have an enum type like this as an example:

public Enum MyEnum {
    enum1, enum2, enum3 };

I'll read a string from config file. What I need itis to parse the string to MyEnum type or null oor not defined. Not sure if the following codescode will work (sorry for not having access to my VS right now):

// example: ParseEnum<MyEnum>("ENUM1", ref eVal);
bool ParseEnum<T>(string value1, ref eVal) where T : Enum
{
  bool bRet = false;
  var x = from x in Enum.GetNames(typeof(T)) where 
       string.Equals(value1, x, StringComparison. OrdinalIgnoreCase)
       select x;
  if (x.Count() == 1 )
  {
    eVal = Enum.Parse(typeof(T), x.Item(0)) as T;
    bRet = true;
  }
  return bRet;
}

Not sure if it is correct or there is any other simple way to parse a string to a MyEnum value?

I have an enum type like this as an example:

public Enum MyEnum {
    enum1, enum2, enum3 };

I'll read a string from config file. What I need it to parse the string to MyEnum type or null o not defined. Not sure if the following codes will work (sorry for not having access to my VS right now):

// example: ParseEnum<MyEnum>("ENUM1", ref eVal);
bool ParseEnum<T>(string value1, ref eVal) where T : Enum
{
  bool bRet = false;
  var x = from x in Enum.GetNames(typeof(T)) where 
       string.Equals(value1, x, StringComparison. OrdinalIgnoreCase)
       select x;
  if (x.Count() == 1 )
  {
    eVal = Enum.Parse(typeof(T), x.Item(0)) as T;
    bRet = true;
  }
  return bRet;
}

Not sure if it is correct or there is any other simple way to parse a string to MyEnum value?

I have an enum type like this as an example:

public Enum MyEnum {
    enum1, enum2, enum3 };

I'll read a string from config file. What I need is to parse the string to MyEnum type or null or not defined. Not sure if the following code will work (sorry for not having access to my VS right now):

// example: ParseEnum<MyEnum>("ENUM1", ref eVal);
bool ParseEnum<T>(string value1, ref eVal) where T : Enum
{
  bool bRet = false;
  var x = from x in Enum.GetNames(typeof(T)) where 
       string.Equals(value1, x, StringComparison. OrdinalIgnoreCase)
       select x;
  if (x.Count() == 1 )
  {
    eVal = Enum.Parse(typeof(T), x.Item(0)) as T;
    bRet = true;
  }
  return bRet;
}

Not sure if it is correct or there is any other simple way to parse a string to a MyEnum value?

edited tags
Link
Rex M
  • 144.4k
  • 34
  • 292
  • 315
edited tags
Link
Rex M
  • 144.4k
  • 34
  • 292
  • 315
Source Link
David.Chu.ca
  • 39.1k
  • 66
  • 154
  • 199
Loading