Search code examples
c#enumsnullable

Deferred property for nullable enum


When I have an optional property in a class which can be null, I use the following pattern to defer it. I also use variations for value types such as integers.

    string myType;
    public string MyType
    {
        get { return myType ?? (myType = GetMyType()); }
    }

I'm trying to do the same with an enum - I would have expected the pattern to be something like this:

    MyEnum? myEnum;
    public MyEnum MyEnum
    {
        get { return myEnum ?? (myEnum = GetMyEnum()); }
    }

However, I'm getting an error stating that I can not explicitly make this conversion - anyone got an idea as to how I can get around it?


Solution

  • The result of the (myEnum = GetMyEnum()) assignment is a MyEnum? because myEnum is MyEnum?; so you'll need to add a .Value or .GetValueOrDefault() after the (...).

    This works, for example:

    public MyEnum MyEnum => myEnum ?? (myEnum = GetMyEnum()).GetValueOrDefault();
    

    as does:

    public MyEnum MyEnum => myEnum ?? (myEnum = GetMyEnum()) ?? 0;
    

    or in C# 7.1:

    public MyEnum MyEnum => myEnum ?? (myEnum = GetMyEnum()) ?? default;