I was reading official Microsoft C# documentation and examples on ENUM and there is a code in example that I don't understand.
public enum Season
{
Spring,
Summer,
Autumn,
Winter
}
public class EnumConversionExample
{
public static void Main()
{
Season a = Season.Autumn;
Console.WriteLine($"Integral value of {a} is {(int)a}"); // output: Integral value of Autumn is 2
var b = (Season)1;
Console.WriteLine(b); // output: Summer
var c = (Season)4;
Console.WriteLine(c); // output: 4
}
}
The code block in question is
var c = (Season)4;
Documentation says that values in ENUM are associated with INTs that start with 0 and increase by 1 for each next value. So by this logic, Spring is 0, Summer is 1, Autumn is 2 and Winter is 3. There is no ENUM value associated with 4, yet VS shows not error and prints 4 when I run it.
I don't understand this behavior and it looks strange that VS doesn't mark this code block as error or warning. Wouldn't it be better to let a program crash to prevent more bugs when you try to retrieve a value from ENUM that doesn't even exist?