Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Why do nullable bools not allow if(nullable) but do allow if(nullable == true)?

This code compiles:

private static void Main(string[] args)
{
    bool? fred = true;

    if (fred == true)
        Console.WriteLine("fred is true");
    else if (fred == false)
         Console.WriteLine("fred is false");
    else Console.WriteLine("fred is null");
}

This code does not compile.

private static void Main(string[] args)
{
    bool? fred = true;

    if (fred)
        Console.WriteLine("fred is true");
    else if (!fred)
         Console.WriteLine("fred is false");
    else Console.WriteLine("fred is null");
}

I thought if(booleanExpression == true) was supposed to be a redundancy. Why isn't it in this case?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There's no implicit conversion from Nullable<bool> to bool. There is an implicit conversion from bool to Nullable<bool> and that's what happens (in language terms) to each of the bool constants in the first version. The bool operator==(Nullable<bool>, Nullable<bool> operator is then applied. (This isn't quite the same as other lifted operators - the result is just bool, not Nullable<bool>.)

In other words, the expression 'fred == false' is of type bool, whereas the expression 'fred' is of type Nullable<bool> hence you can't use it as the "if" expression.

EDIT: To answer the comments, there's never an implicit conversion from Nullable<T> to T and for good reason - implicit conversions shouldn't throw exceptions, and unless you want null to be implicitly converted to default(T) there's not a lot else that could be done.

Also, if there were implicit conversions both ways round, an expression like "nullable + nonNullable" would be very confusing (for types that support +, like int). Both +(T?, T?) and +(T, T) would be available, depending on which operand were converted - but the results could be very different!

I'm 100% behind the decision to only have an explicit conversion from Nullable<T> to T.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...