0

I was hoping to get some help with this. I need a function that can take in a string that is a key for a dictionary and an enum type that is has to be cast to.

The dictionary key will be a number that corresponds to an enum. I need to know how to cast the int into an enum where the enum is variable.

Here is the function as I have it written. This might be more clear than my explanation.

string GetEnum(string keyName, Enum enumType)
{
    var defaultOut = "";
    Model.Form.TryGetValue(keyName, out defaultOut);
    if(defaultOut != ""){
        return EnumDescriptionUtility.GetDescription((enumType)Convert.ToInt32(defaultOut));            
    }
    else{
        return defaultOut;    
    } 
}

I have used most of this code before. the difference before was that enumType was hard coded to the actual enum. I want to offload all that repetition to a function.

Any help is appreciated.

9
  • There are a lot of potential problems here. Are you validating any of your conversions? Also, why convert a string to an int and then to an enum...why not just convert from the string to an enum? Or better yet, why not just ditch the string entirely and work with enums (i.e. as an output to TryGetValue)? Commented Jan 27, 2017 at 19:32
  • I could add a check for a bad conversion. The string comes out of the database. So I need to convert it to the enum to get the enum's description which is the user facing nice version. Commented Jan 27, 2017 at 19:35
  • I'm just wondering why, if your defaultOut will always be passed to Convert.ToInt32, why is it a string at all? Why not just an int? Or, like i said, why not make it an enum? Commented Jan 27, 2017 at 19:36
  • The dictionary is <string, string> so it will always require a conversion to an Int. Commented Jan 27, 2017 at 19:38
  • That's what I'm getting at...change the dictionary to <string, int> or <string, YourEnumType> Commented Jan 27, 2017 at 19:38

3 Answers 3

1

I'm not 100% sure I understand your Q, though if i do, you want to cast a value to a given enum?

This is an extension method I created recently to parse a value to a given enum. The value in this case is the string name of the enum.

public static T ToEnum<T>(this string val) where T : struct
{
     T t;
     if (Enum.TryParse(val, out t))
          return t;
     return default(T);
}

And you would use it like:

public enum MyEnum{
  A = 1,
  B = 2,
  C = 3
}

public enum MyOtherEnum{
  D = 1,
  E = 2,
  F = 3
}


string str = "A";
MyEnum yourEnum = str.ToEnum<MyEnum>();

string str2 = "A";
MyOtherEnum yourOtherEnum = str.ToEnum<MyOtherEnum>();
Sign up to request clarification or add additional context in comments.

2 Comments

This is close, but all the enums run off integers.
with an int you can simply do MyEnum myEnum = (MyEnum)YourInt or MyEnum myEnum = (MyEnum)Convert.ToInt32(YourIntAsAString) - you have an example of one of your actual enums you can add?
0

So if I understand you correctly, you know they type of enum and the integer value. You didn't include any information about your enums so I set up a simple example.

    public enum Letter
    {
        A,
        B,
        C
    }

    public enum Number
    {
        One,
        Two,
        Three
    }

So if you know the type and integer value, you can get an enum like this:

    public static Enum GetEnum(Type type, int val)
    {
        Enum e = null;

        if (type == typeof(Letter))
        {
            e = (Letter)val;
        }
        else if (type == typeof(Number))
        {
            e = (Number)val;
        }

        return e;
    }

You will need to inspect its type to use it. Maybe like this:

    public static string StringFromEnum(Enum e)
    {
        string result = null;

        if (e.GetType() == typeof(Letter))
        {
            result =  ((Letter)e).ToString();
        }
        else if (e.GetType() == typeof(Number))
        {
            result = ((Number)e).ToString();
        }

        return result;
    }

    public static void Main(string[] args)
    {
        int val1 = 2;
        Type type1 = typeof(Letter);
        int val2 = 0;
        Type type2 = typeof(Number);

        var result1 = GetEnum(type1, val1);
        var result2 = GetEnum(type2, val2);

        Console.WriteLine("result1 {0}", StringFromEnum(result1));
        Console.WriteLine("result2 {0}", StringFromEnum(result2));

        Console.ReadKey();
    }

1 Comment

The issue is having too many enums to cast to. I was hoping to be able to pass a variable of that enum type and use that to cast the int or at least get the type from that. The function shouldn't care what enum it gets.
0

If you just want to get a string representing the name of the enum for a given type and int, you can do the following using Enum.GetName()

    public enum Letter
    {
        A,
        B,
        C
    }

    public enum Number
    {
        One,
        Two,
        Three
    }

    public static void Main(string[] args)
    {
        int val1 = 2;
        Type type1 = typeof(Letter);
        int val2 = 0;
        Type type2 = typeof(Number);

        var result1 = Enum.GetName(type1, val1);
        var result2 = Enum.GetName(type2, val2);

        Console.WriteLine("result1 {0}", result1);
        Console.WriteLine("result2 {0}", result2);

        Console.ReadKey();
    }

If you want the actual enum, I think you have to do something similar to the other answers. It sounds like you want to cast using a Type variable:

Type type1 = typeof(Letter);
var result = (type1) val1;  // wrong

And I don't think you can do that. Even with generics you will have to specify type at some point.

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.