Archive for the ‘Surprising things in c#’ Category

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’

Advertisements