Skip to content

Unexpected results casting from null instance #566

@Conman-123

Description

@Conman-123

If I have a SmartEnum with a non-nullable TValue (like MySmartEnum : SmartEnum<MySmartEnum, byte>), casting a null instance of this enum returns a non-null value:

MySmartEnum? enumValue = null;
byte? dbRawValue = enumValue; // Converts to 0 rather than null
byte? dbRawValue2 = (byte?)enumValue; // Same issue

This has caught me out a few times, and I only notice it when I then try parsing the value back and it throws because there is no MySmartEnum with value 0.

The nullable generic logic is very confusing to me so I'm not sure if it's possible to make this work generically.

My workaround is to inherit from a custom non-generic subclass with a fully qualified implicit cast operator:

public class CustomSmartEnum<TEnum> : SmartEnum<TEnum, byte> where TEnum : SmartEnum<TEnum, byte>
{
    public CustomSmartEnum(string name, byte value) : base(name, value) { }

    public static implicit operator byte?(CustomSmartEnum<TEnum>? smartEnum) =>
        smartEnum?.Value;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions