While messing around with enums, I found out a strange behaviour of one of my enums.
Consider the following code :
static void Main()
{
Console.WriteLine("Values");
Console.WriteLine();
foreach (Month m in Enum.GetValues(typeof(Month)))
{
Console.WriteLine(m.ToString());
}
Console.WriteLine();
Console.WriteLine("Names");
Console.WriteLine();
foreach (var m in Enum.GetNames(typeof(Month)))
{
Console.WriteLine(m);
}
Console.ReadLine();
}
public enum Month
{
January,
May,
March,
April
}
This code produces the following output (as expected):
Values
January
May
March
April
Names
January
May
March
April
Now, lets say I change a little bit my enum, like this :
public enum Month
{
January = 3,
May,
March,
April
}
If I run the same code, the same results will apear (which is strange as it is). Now if I change my enum like this :
public enum Month
{
January = "g",
May,
March,
April
}
I get the following compiler error :
Cannot implicitly convert type 'string' to 'int'.
Why the compiler allows me to set one of the values of the enum to 3, but not to g? And why the first result is exactly like the second one? If I changed the value of January, then why GetValues
doesnt print 3?