Can anyone explain this?
alt text http://www.deviantsart.com/upload/g4knqc.png
using System; namespace TestEnum2342394834 { class Program { static void Main(string[] args) { //with "var" foreach (var value in Enum.GetValues(typeof(ReportStatus))) { Console.WriteLine(value); } //with "int" foreach (int value in Enum.GetValues(typeof(ReportStatus))) { Console.WriteLine(value); } } } public enum ReportStatus { Assigned = 1, Analyzed = 2, Written = 3, Reviewed = 4, Finished = 5 } }
The GetValues method returns an array that contains a value for each member of the enumType enumeration. If multiple members have the same value, the returned array includes duplicate values.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Enum names are in global scope, they need to be unique.
Enum.GetValues
is declared as returning Array
.
The array that it returns contains the actual values as ReportStatus
values.
Therefore, the var
keyword becomes object
, and the value
variable holds (boxed) typed enum values.
The Console.WriteLine
call resolves to the overload that takes an object
and calls ToString()
on the object, which, for enums, returns the name.
When you iterate over an int
, the compiler implicitly casts the values to int
, and the value
variable holds normal (and non-boxed) int
values.
Therefore, the Console.WriteLine
call resolves to the overload that takes an int
and prints it.
If you change int
to DateTime
(or any other type), it will still compile, but it will throw an InvalidCastException
at runtime.
According to the MSDN documentation, the overload of Console.WriteLine
that takes an object
internally calls ToString
on its argument.
When you do foreach (var value in ...)
, your value
variable is typed as object
(since, as SLaks points out, Enum.GetValues
returns an untyped Array
) and so your Console.WriteLine
is calling object.ToString
which is overriden by System.Enum.ToString
. And this method returns the name of the enum.
When you do foreach (int value in ...)
, you're casting the enum values to int
values (instead of object
); so Console.WriteLine
is calling System.Int32.ToString
.
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