Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

c# - if condition with nullable

There is a lot of syntax sugar with Nullable<T> like those:

int? parsed to Nullable<int>

int? x = null
   if (x != null) // Parsed to if (x.HasValue)

x = 56; // Parsed to x.Value = 56;

And more.

Why if condition with Nullable doesn't work?

if (x)
{} 

It gets Complier error saying can't convert Nullable<bool> to bool.
Why it's not being parsed to if (x.HasValue && x.Value == true) or something similar?

It's the most obvious usage for Nullable<bool>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's the most obvious usage for Nullable<bool>

Your "obvious" behaviour leads to many inobvious behaviours.

If

if(x)

is treated as false when x is null, then what should happen to

if(!x)

? !x is also null when x is null, and therefore will be treated as false also! Does it not seem strange that you cannot reverse the behaviour of a conditional with an inversion?

What about

if (x | !x)

Surely that should always be true, but if x is null then the whole expression is null, and therefore false.

It is better to avoid these inobvious situations by simply making them all illegal. C# is a "make the user say what they mean unambiguously" language.

I believe that VB has the behaviour you want. You might consider switching to VB if this is the sort of thing you like.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...