开发者

C# cast object of type int to nullable enum

I just need to be able to cast an object to nullable enum. Object can be enum, null, or int. Thanks!

public enum MyEnum { A, B }
void Put(object value)
{
    System.Nullable<Myenum> val = (System.Nullable<MyEnum>)value开发者_运维百科;
}

Put(null);     // works
Put(Myenum.B); // works
Put(1);        // Invalid cast exception!!


How about:

MyEnum? val = value == null ? (MyEnum?) null : (MyEnum) value;

The cast from boxed int to MyEnum (if value is non-null) and then use the implicit conversion from MyEnum to Nullable<MyEnum>.

That's okay, because you're allowed to unbox from the boxed form of an enum to its underlying type, or vice versa.

I believe this is actually a conversion which isn't guaranteed to work by the C# spec, but is guaranteed to work by the CLI spec. So as long as you're running your C# code on a CLI implementation (which you will be :) you'll be fine.


This is because you're unboxing and casting in a single operation, which is not allowed. You can only unbox a type to the same type that is boxed inside of the object.

For details, I recommend reading Eric Lippert's blog: Representation and Identity.


a bit offtopic

For Those, who needs the result to be null when the value is not defined in the enum;

One should use either :

typeof(MyEnum).IsEnumDefined(val)

or

Enum.IsDefined(typeof(MyEnum), val)

Here is the usage example:

enum MyEnum { one = 1, three = 3, four=4 }

static MyEnum? CastIntAsNullableEnum(int value) 
{
    if (!Enum.IsDefined(typeof(MyEnum), value)) return null;
    return (MyEnum?)value;            
}

static void CastIntAsNullableEnumTest()
{
    for(int i =0; i<=5; i++)
    {
        Console.WriteLine("converted {0} is {1}", i, CastIntAsNullableEnum(i));
    }                        
}

Thanks to John Thiriet (johnthiriet.com) for the solution


When you are assigning a value to a nullable type you have to be aware that it is not the same as the underlying type(at least in this case). So in order to perform the cast you need to unbox first:

void Put(object value)
{
    if (value != null)
    {
        System.Nullable<Myenum> val = (System.Nullable<MyEnum>)(MyEnum)value;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜