Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this allowed in C#? [closed]

Tags:

c#

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#?

like image 499
ckv Avatar asked Jul 29 '13 10:07

ckv


2 Answers

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.

like image 56
Marc Gravell Avatar answered Sep 30 '22 19:09

Marc Gravell


C# unlike C++, does not implicitly cast integer to bool.

like image 31
Anthony Garcia-Labiad Avatar answered Sep 30 '22 18:09

Anthony Garcia-Labiad