0

I'm trying to get a enum value from a string in a database, below is the enum I am trying to get the value from, the DB value is a string.

internal enum FieldType
{
    Star,
    Ghost,
    Monster,
    Trial,
    None
}

Heres the DB part:

using (var reader = dbConnection.ExecuteReader())
{
    var field = new Field(
        reader.GetString("field_type"),
        reader.GetString("data"),
        reader.GetString("message")
    );
}

Now, I had this method that did it for me, but it seems overkill to have a method do something that C# could already do, can anyone tell me if theres a way I can do this within the C# language without creating my own method?

public static FieldType GetType(string Type)
{
    switch (Type.ToLower())
    {
        case "star":
            return FieldType.Star;

        case "ghost":
            return FieldType.Ghost;

        case "monster":
            return FieldType.Monster;

        case "trial":
            return FieldType.Trial;

        default:
        case "none":
            return FieldType.None;
    }
}

2 Answers2

4

In essence, I believe what you need is parsing from string to an enum. This would work if the value of the string is matching the enum value (in which it seems it is here).

Enum.TryParse(Type, out FieldType myFieldType);


Enum.TryParse(Type, ignoreCase, out FieldType myFieldType);

First method case-sensitive while the second allows you to specify case sensitivity.

How should I convert a string to an enum in C#?

tiunovs
  • 71
  • 1
  • 3
hsoesanto
  • 513
  • 2
  • 9
  • The only problem I thought about with this was caps sensitive, that the enum had a capital for the first character and the string didn't, I guess that wouldn't matter? – s3550191 Dec 16 '17 at 12:36
  • There's an overload that lets you request case-insensitive parsing – Jon Hanna Dec 16 '17 at 13:07
4

Let's define a test string first:

String text = "Star";

Before .NET 4.0 (MSDN reference):

// Case Sensitive
FieldType ft = (FieldType)Enum.Parse(typeof(FieldType), text, false);

// Case Insensitive
FieldType ft = (FieldType)Enum.Parse(typeof(FieldType), text, true);

but with Enum.Parse you have to manage a potential exception being thrown if the parsing process fails:

FieldType ft;

try
{
    ft = (FieldType)Enum.Parse(typeof(FieldType), text, true);
}
catch (Exception e)
{
    ft = FieldType.None;
}

Since .NET 4.0 (MSDN reference):

FieldType ft;

// Case Sensitive
if (!Enum.TryParse(text, false, out ft))
    ft = FieldType.None;

// Case Insensitive
if (!Enum.TryParse(text, true, out ft))
    ft = FieldType.None;
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98