I have the following if condition param.days
is a string.
if (param.days != null)
This works fine, but if I say
If (param.days)
then it does not evaluate correctly at runtime. Both statements are not the same in C#.
It does say that the value is null but then C# tries to cast it to a bool which is non-nullable.
Why did the C# designers choose to do it this way?
Such a statement is valid in C++, but why is this not considered valid in C#?
Such a statement is valid in C++, but why is this not considered valid in C#
Because C# assumes different languange rules. It does not assume that every number / reference can be treated as a boolean by checking if it is zero vs non-zero, null vs non-null. If you want to test whether something is null: test whether it is null.
Note: if days
is actually a T?
(aka Nullable<T>
), then you can check:
if(param.days.HasValue)
which is then identical to if(param.days != null)
Alternatively, if your type can sensibly be treated as a boolean, then there are operators you can override to tell the compiler that.
C# unlike C++, does not implicitly cast integer to bool.
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