views:

3344

answers:

3

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?

+2  A: 

I think you will just need to cast the result to (MyEnum?) rather than (MyEnum)?

+4  A: 

There is a syntax error in your code: the position of ':' and '?' must be exchanged:

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

BTW:

as far as I know, the recommended way is to use a enum-element named 'None' instead of a Nullable enum, e.g:

public enum MyEnum
{
    None, Value1, Value2, Value3
}

and

MyClassEnum = Convert.IsDBNull(x) ? MyEnum.None : 
            (MyEnum) Enum.Parse(typeof(MyEnum), x.ToString(), true);
M4N
+6  A: 

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)
Luke Quinane
MyClassEnum must also be nullable (obviously).
Robert C. Barth
Thanks....That solved my issue.
Michael Kniskern