Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result when using Enum.Parse()

Tags:

c#

enums

parsing

class Program
{
    static void Main(string[] args)
    {
        String value = "Two";
        Type enumType = typeof(Numbers);
        Numbers number = (Numbers)Enum.Parse(enumType, value);
        Console.WriteLine(Enum.Parse(enumType, value));
    }

    public enum Numbers : int
    {
        One,
        Two,
        Three,
        Four,
        FirstValue = 1
    }
}

This is a simplified version of an enum I use in an application. The reason to why some of the enum names doesn't have a value is because I do Enum.Parse with their names as argument, while the ones with a value is parsed from an int.

If you would step through the code above and investigate the 'number' variable, you would see that it in fact is 'Two', but the output in console is 'FirstValue'. At this point I can't see why, do you?

Okay, the solution is simple - just give the valueless enums a value. But I'm still curious.

like image 848
Portablenut Avatar asked Sep 13 '26 03:09

Portablenut


1 Answers

I suspect that both FirstValue and Two have an internal value of 1, so the system doesn't know which string to output.

public enum Numbers : int
{
    One, // defaults to 0
    Two, // defaults to 1
    Three, // defaults to 2
    Four, // defaults to 3
    FirstValue = 1 // forced to 1
}

There is a unique integer value for every enum value, but there is not a unique enum value for every integer value.

When you parse "two", it gets stored internally as the integer 1. Then when you try and convert it back to a string, depending on the technique used to lookup that name, you could get either "Two" or "FirstValue". As you stated, the solution is to give every enum value a defined integer value.

like image 145
Eclipse Avatar answered Sep 14 '26 16:09

Eclipse