Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why enums with default values are not working as expected in C#?

Tags:

c#

enums

c#-4.0

I was going through Jon skeet website on C# Brain teasers http://www.yoda.arachsys.com/csharp/teasers.html. Why item "Baz" is showing in the output even though I declared default values for all items in enum

---eg:1

class Test
{

    enum Foo { Bar, Baz,bread, jam };

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
// output :Bar

--eg2

class Test
{
    enum Foo { Bar, Baz,bread=0, jam };

    const int One = 1;
    const int Une = 1;


    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
//output : Bar

--eg3

class Test
{
    enum Foo { Bar, Baz=0, bread=0, jam };

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
//output :Baz

--eg4

class Test
{
    enum Foo { Bar=0, Baz=0, bread=0, jam=0};

    const int One = 1;
    const int Une = 1;


    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
//output:Baz
like image 695
Hemanth Krishna Avatar asked Jun 07 '17 11:06

Hemanth Krishna


People also ask

Can enums have default value?

The default value for an enum is zero.

What is the default value of enum in C?

In C programming, an enumeration type (also called enum) is a data type that consists of integral constants. To define enums, the enum keyword is used. enum flag {const1, const2, ..., constN}; By default, const1 is 0, const2 is 1 and so on.

What is default value of first enum constant in C?

If the first value of the enum variable is not initialized then the C compiler automatically assigns the value 0.

Are enums 0 based?

Enum ValuesThe first member of an enum will be 0, and the value of each successive enum member is increased by 1. You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.


1 Answers

Enums are just integers to .NET. Any time you think of them as a name (like ToString(), you're actually saying "try to find a defined enum label that matches the integer value, and tell me the name of that". In this case, you have multiple enum labels with the same integer value, so which name in WriteLine is undefined. Note that WriteLine here is ultimately doing f.ToString(), which applies the "find a value" logic from above.

For --eg5, I would propose: Foo f = (Foo)-1327861;. Perfectly valid in .NET terms, but doesn't match any enum definition. It doesn't have to.

like image 191
Marc Gravell Avatar answered Sep 20 '22 21:09

Marc Gravell