4

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 

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

Comments

3

For a Nullable<T>, you have a HasValue property, and a Value property. Your cast is valid, but this would work too (and looks better to me):

if (value.HasValue)
{
    Foo(value.Value);
}

Comments

3

Instead of casting it you should pass value.Value. The Nullable-type has a Value-property that contains the actual value - in case it's not null. When the value is null and you try to access this property you'll get an Exception.

4 Comments

@ilansch, you have accepted the worst answer.. exception driven development is not considered to be a best practice
took in mind, For my concern, answer was to use .value when requesting the value of nullable. regarding to implementation and actually using - I have entry point that i verify the given enum is not null and then sending the .value
@MichalKlouda I have nowhere mentioned exception driven development. I said instead of his casting he should access Value, and pointed out that this will throw an Exception in case if it's null. Of course he should first check if there's an value with HasValue, like he does already.
@JustAnotherUserYouMayKnow yes, sorry, I didn't want to offend you and I am not saying your answer is wrong.. I just wanted to point out, that it's not always the best approach to use exceptions for such things

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.