Sei sulla pagina 1di 3

How to: Safely Cast from bool?

to bool (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/bb384091

1 of 3

5/25/2012 11:48 AM

How to: Safely Cast from bool? to bool (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/bb384091

How to: Safely Cast from bool? to bool (C# Programming Guide)
Visual Studio 2010 1 out of 1 rated this helpful - Rate this topic The bool? nullable type can contain three different values: true, false, and null. Therefore, the bool? type cannot be used in conditionals such as with if, for, or while. For example, the following code causes a compiler error.

bool? b = null; if (b) // Error CS0266. { } This is not allowed because it is unclear what null means in the context of a conditional. To use a bool? in a conditional statement, first check its HasValue property to ensure that its value is not null, and then cast it to bool. For more information, see bool. If you perform the cast on a bool? with a value of null, a InvalidOperationException will be thrown in the conditional test. The following example shows one way to safely cast from bool? to bool:

Example
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. }

See Also
Reference Literal Keywords (C# Reference) Nullable Types (C# Programming Guide) Concepts C# Programming Guide

Did you find this helpful?

Yes

No

2 of 3

5/25/2012 11:48 AM

How to: Safely Cast from bool? to bool (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/bb384091

Community Content
Use ?? as a shortcut
You may be able to use the ?? operator as a shortcut here. Especially handy when dealing with typecast objects with bool? properties, as an alternative to multiple conditionals each with their own cast, or havi ng to declare a temporary:
foreach (ListBoxItem item in listBox1.Items) { if ((item.Content as CheckBox).IsChecked ?? false) { // Do something } }

5/4/2010 Tim Keating

2012 Microsoft. All rights reserved.

3 of 3

5/25/2012 11:48 AM

Potrebbero piacerti anche