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;
    }
}
1
  • What is the value of string Type before you call .ToLower() on it? Commented Dec 16, 2017 at 13:07

2 Answers 2

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#?

Sign up to request clarification or add additional context in comments.

2 Comments

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?
There's an overload that lets you request case-insensitive parsing
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.