I 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 example, reading data as follows:
string field = datareader["column"].As("default value when null")
But this will not work when I want to translate to a null enumeration from the value in the box. The best I could come up with is (dirty WIP code that 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;
}
}
Using:
public enum SomeEnum {Value1, Value2};
object value = 1;
var result = value.As<SomeEnum?>();
The current error is an InvalidCastException when it tries to pass Int32 to a null enumeration. Which is normal, I think, but I don’t know how else could I do this? I tried to create an instance of nullable enum T and assign a value to it, but I was fixated on how exactly this can be done.
Any idea or best way to solve this problem? Is it possible to solve this in general? I searched a lot, but I did not find anything useful.