-
-
Notifications
You must be signed in to change notification settings - Fork 186
Unexpected results casting from null instance #566
Copy link
Copy link
Open
Description
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 issueThis 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;
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels