Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable Enum nullable type question

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?

like image 321
Michael Kniskern Avatar asked Jan 08 '09 23:01

Michael Kniskern


1 Answers

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)
like image 76
Luke Quinane Avatar answered Sep 22 '22 07:09

Luke Quinane