Nullable Enum nullable type question

Michael Kniskern picture Michael Kniskern · Jan 9, 2009 · Viewed 20.9k times · Source

I get the following compilation error with the following source code:

Compilation Error:

Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'MyEnum'

Source Code

public enum MyEnum
{
    Value1, Value2, Value3
}

public class MyClass
{
    public MyClass() {}
    public MyEnum? MyClassEnum { get; set; }
}

public class Main()
{
   object x = new object();

   MyClass mc = new MyClass()
   {
        MyClassEnum = Convert.IsDBNull(x) : null ? 
            (MyEnum) Enum.Parse(typeof(MyEnum), x.ToString(), true)
   };
}

How can I resolve this error?

Answer

Luke Quinane picture Luke Quinane · Jan 9, 2009

I think you just need to cast the result of Enum.Parse to MyEnum?. This is the case with nullable ints at least. E.g.:

int? i;
i = shouldBeNull ? null : (int?) 123;

So:

MyClassEnum = Convert.IsDBNull(x)
    ? null
    : (MyEnum?) Enum.Parse(typeof(MyEnum), x.ToString(), true)