Interesting behaviours with enum in .NET

When defining an enum type, we can assign an int value to each of the enum members. Below is an example.

enum Status
	Active = 100,
	Inactive = 101

Now there are two behaviours that you may not be aware of. Firstly, given the above definition, you can actually assign any int value to a variable of type Status. Let say I have a class as below.

class Record
	public Status RecordStatus { get; set; }

The following code will then happily compile and execute:

var record = new Record();
record.RecordStatus = (Status)4525424;

OK, who on earth would be doing something like that? Probably not many, but this leads on to the second behaviour: by default, the value of the enum will be 0, even if 0 is not one of the defined enum members.

So with the code below, the value of record.Status will be 0, which does not match any of the defined status values:

var record = new Record();

Console.WriteLine((int)record.RecordStatus); //Display 0
Console.WriteLine(record.RecordStatus == Status.Active); //Display False

This behaviour could have an impact on your code if not handled properly. This is because when defining an enum, we often don’t assign explicit values to the members. We also typically expect record.Status in the code above to default to the first member of the enum. This happens to be correct as the underlying explicit values for enum members start from 0 when not explicitly assigned.

When we assign explicit values however, an uninitialised enum variable no longer equal to any of the defined enum members.

So, the bottom line is, if you assign explicit values to enum members, you should always initialise the enum variable to an appropriate value, for example as below:

class Record
	public Record()
		this.RecordStatus = Status.Active;

	public Status RecordStatus { get; set; }

About Bernado

Based in Australia, I am a freelance SharePoint and Dynamics CRM developer. I love developing innovative solutions that address business and everyday problems. Feel free to contact me if you think I can help you with your SharePoint or CRM implementation.
This entry was posted in .NET. Bookmark the permalink.

1 Response to Interesting behaviours with enum in .NET

  1. Reblogged this on iReadable and commented:
    This is completely plausible and the check is avoid first for performance reasons and then because of versioning. That is why you have Enum.IsDefined(…)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s