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
The default value for an enum is zero.
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.
If the first value of the enum variable is not initialized then the C compiler automatically assigns the value 0.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With