I have enum with values, I set that enum to be Nullable, this due to fact I dont want to add a MyEnum.NotAvilable state. My problem begins when I send this enum as parameter to function, It will display message:
"The best overloaded method .."
I guess this is because the enum is nullable. The only thing that will work is if when sending the enum to function, I cast the enum to MyEnum or change the signature of foo to accept MyEnum? and not MyEnum.
enum is defined:
public MyEnum? Test
calling a function with signature: private void Foo(MyEnum value)
Foo(MyEnum value); // not working
Foo(MyEnum? value); // works
My question is - Is it bad practice to cast to MyEnum before sending it to Foo ?
if (value.HasValue)
Foo((MyEnum) value); //this makes Foo(MyEnum value) valid
If your function knows what to do with a null value for your enum, send MyEnum?. If it doesn't, you have two choices - not to send to the method at all if your value is null, or to send a default value instead.
if (value.HasValue)
Foo(value.Value);
//or, send a default (null coalescing operator)
Foo(value ?? MyEnum.SomeValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With