Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sending Nullable enum as parameter

Tags:

c#

nullable

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 
like image 226
ilansch Avatar asked Oct 25 '25 14:10

ilansch


1 Answers

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);
like image 164
sq33G Avatar answered Oct 28 '25 05:10

sq33G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!