I am trying to write an extension method which, given the value, will return
- The value itself, if it is different from
DBNull.Value - The default
value for value type
Yes, this is not the clearest explanation, maybe some code will do what I'm trying to make obvious.
public static T GetValueOrDefault<T>(this object value) { if (value == DBNull.Value) return default(T); else return (T)value; }
As long as the value type in the box matches T , this method works correctly.
Real funny punches when the types are different, for example, the box value of byte and T is int .
Is there an elegant way to make this work?
Performing some type checks manually for the first transfer from, for example. object to byte , and then from byte to T , of course, won't work.
Edit
The proposed solution should also work with enumerations not only with standard types.
source share