17 May 2012

C# - Initialization of enums

I notice that I want to write too much based on what I have read in Effective C#, so I'll post bits and pieces instead of one big article, here comes a small one:

Initialization and enums

If an object is instantiated all member variables are initialized, with a given initializer or 0/null if none was specified. References are always null, bools are always false, number values are 0, and... enums are set to 0.

Wow! I never realized that, I kinda assumed that an enum value was set to the first value defined in the enum, but this is clearly not the case - and shouldn't be. It does imply that you always need to have a 0-value in your enums, or you risk having an enum variable with an undefined value. Also, when using the [Flags] modifier, None = 0.