Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the big difference? casting or testing for value difference in an if statement

Tags:

c#

In this case my variable Truth is a nullable variable. My question is simple

Would there be anything wrong writing it like this?

if ((bool)Truth) {}

or should i stick with this?

if (Truth == True) {}

Never worked with nullable variables not certain if there is even a difference other then possibly if ((bool)Truth) {} taking one additional step?

like image 983
Don Thomas Boyle Avatar asked Feb 15 '23 02:02

Don Thomas Boyle


2 Answers

These are semantically different. If Truth is null, the cast will fail with an InvalidOperationException: Nullable object must have a value. The second one will not fail and just execute if the value has true in it. Unless null should be an invalid value at this point in your program, go with the second version.

like image 177
Jesse C. Slicer Avatar answered May 12 '23 02:05

Jesse C. Slicer


As stated be Jesse Slicer, nullable values could be casted to their non-nullable equivalent type only if you're sure they are not null. Even in this case, I would not do it since it may not be the most readable way to do it.

The best way to use a nullable boolean is :

if (myBool.HasValue && myBool.Value)

This ensures that myBool is not null (HasValue) and is true (Value returns the boolean value). Note that this example assumes that you do not want to enter the if statement if your nullable bool is null.

By the way, all nullable types provides a HasValue and a Value property. I'd rather use the Value property than a cast since it clearly states that you're manipulating a nullable type.

like image 34
Marshall777 Avatar answered May 12 '23 02:05

Marshall777