How: From bool? Securely forcibly convert to bool (C # programming guide)

Source: Internet
Author: User

Bool? The data type that can be null can contain three different values: True, false, and null. So bool? Type cannot be used in conditional statements, such as if, for, or while. For example, this Code cannot be compiled and a compiler error cs0266 will be reported:

bool? b = null;
if (b) // Error CS0266.
{
}


This is not allowed, because the meaning of null in the context of the condition is unclear. To use bool? In a condition statement ?, First check its hasvalue attribute to ensure that its value is not null, and then forcibly convert it to bool. For more information, see bool. If the bool of a null value is used? If a forced conversion is executed, invalidoperationexception is thrown in the condition test. The following example demonstrates a kind? Safely cast to bool:

           bool? test = null;             ...// Other code that may or may not                // give a value to test.            if(!test.HasValue) //check for a value            {                // Assume that IsInitialized                // returns either true or false.                test = IsInitialized();            }            if((bool)test) //now this cast is safe            {               // Do something.            }

From

How: From bool? Securely forcibly convert to bool (C # programming guide)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.