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
}
}
Enum.GetValuesis declared as returningArray.The array that it returns contains the actual values as
ReportStatusvalues.Therefore, the
varkeyword becomesobject, and thevaluevariable holds (boxed) typed enum values.The
Console.WriteLinecall resolves to the overload that takes anobjectand callsToString()on the object, which, for enums, returns the name.When you iterate over an
int, the compiler implicitly casts the values toint, and thevaluevariable holds normal (and non-boxed)intvalues.Therefore, the
Console.WriteLinecall resolves to the overload that takes anintand prints it.If you change
inttoDateTime(or any other type), it will still compile, but it will throw anInvalidCastExceptionat runtime.