I have my program as below:
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
char _status = 'C';
Console.WriteLine(_status.ToString());
if (Enum.IsDefined(typeof(MyStatus), _status.ToString()))
{
Console.WriteLine("Yes1");
}
else
{
Console.WriteLine("No1");
}
MyStatus myStatus;
if(Enum.TryParse(_status.ToString(), true, out myStatus))
{
Console.WriteLine("Yes2");
}
else
{
Console.WriteLine("No2");
}
}
public enum MyStatus
{
None = 'N',
Done = 'C'
//Other Enums
}
}
}
I am expecting "Yes1" and "Yes2" in my Console, but looks like it is returning false for the TryParse and IsDefined. Any helps are appreciated.
The code can be accessed at http://rextester.com/CSFG46040
Update
This value basically comes from a database and gets mapped to a character field. I also need to get it exposed to the programs which already uses this character field as an Enum. The Enum.IsDefined or Enum.TryParse is just to make sure that I am not getting any other junk characters which would get resolved to None.
Yes, that's because your enum is effectively:
public enum MyStatus
{
None = 78,
Done = 67
}
So "N" is neither the name of an enum value, nor is it the decimal representation. Both "None" and "78" would parse to MyStatus.None
, but "N" won't.
It sounds like you quite possibly want a Dictionary<char, MyStatus>
. If you want to treat the numeric value of each enum value as a char, you could build that with:
var dictionary = Enum.GetValues(typeof(MyStatus))
.Cast<MyStatus>()
.ToDictionary(x => (char) x);
See more on this question at Stackoverflow