I've made the following extension method ...
public static class ObjectExtensions
{
public static T As<T>(this object pObject, T pDefaultValue)
{
if (pObject == null || pObject == DBNull.Value)
return pDefaultValue;
return (T) pObject;
}
}
... which i use for e.g. reading data like so:
string field = datareader["column"].As("default value when null")
But it doesn't work when i want to cast to a nullable enum from a boxed value. The best i could come up with was this (messy WIP code which doesn't work):
public static class ObjectExtensions
{
public static T As<T>(this object pObject, T pDefaultValue)
{
if (pObject == null || pObject == DBNull.Value)
return pDefaultValue;
var lType = typeof (T);
if (!IsNullableEnum(lType))
return (T) pObject;
var lEnumType = Nullable.GetUnderlyingType(lType);
var lEnumPrimitiveType = lEnumType.GetEnumUnderlyingType();
if (lEnumPrimitiveType == typeof(int))
{
var lObject = (int?) pObject;
return (T) Convert.ChangeType(lObject, lType);
}
throw new InvalidCastException();
}
private static bool IsNullableEnum(Type pType)
{
Type lUnderlyingType = Nullable.GetUnderlyingType(pType);
return (lUnderlyingType != null) && lUnderlyingType.IsEnum;
}
}
Usage:
public enum SomeEnum {Value1, Value2};
object value = 1;
var result = value.As<SomeEnum?>();
The current error is an InvalidCastException when it tries to cast an Int32 to the nullable enum. Which is ok i guess, but i've no idea how else i could do that? I've tried to create an instance of the nullable enum T and assign it a value, but i'm stuck on how exactly this can be done.
Anyone an idea or a better way to solve this? Is it even possible to solve that in a generic way? I've done quite a lot of searching on that, but i've not found anything useful.