When defaults are invalid

Posted: June 12, 2008 in c#, Surprising things in c#

I was coding a simple method today it looked like this:

public static T Parse(object value){
if (value != null && Enum.IsDefined(typeof(T), value)) {
return (T)value;
return default(T);
}(We have a method that handles string values, which is why the cast is safe if the value is defined for T)

We didn’t like it, mostly because netiher of us liked to hide the invalid/malformed input by returning a default value. But it made us wonder about this statement:

Enum.IsDefined(typeof(T), default(T)) if T is an enumeration would that statement always be true?
The answer is actually no.

To see why let’s define an enum:
public enum MyEnum{
firstValue = 4,
secondValue = 3

Then the statement would be false where as default(MyEnum) == 0 is true.
so the lesson is: Don’t count on default(T) being a valid value.

I would have liked the default value to be either 3 (because it’s the lowest) or 4 because it’s the first value declared.
If you don’t declare the value explicitly the value declared first in the enum is the default value, so I preferre the later to the first.

Update: Part of the reason why we had the talk on enums in the first place was a refactoring process very much like the one described in this nice post

Update: For other coding surprises you might want to have a look at ‘things that make me go hmm’


Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s