Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign NULL value to Boolean variable

Tags:

variables

c#

I am trying to assign null value to Boolean variable but it is not taking it

bool b = null; 
like image 530
Student Avatar asked Mar 19 '11 13:03

Student


People also ask

Can null be assigned to a boolean variable?

Boolean variable cannot have a value of null - is a correct one. We can create a Boolean variable which have null value by assigning it "-1" that represents "null Boolean value". Boolean variable cannot have a value of null because it is a non-nullable value type. Answer is 1 & 5.

How do you set a boolean to null values?

You could use a string instead of boolean and set it to "False", "True" or "" where the empty string represents your null value. Alternatively you need for every Boolean an extra Boolean like <attribute>IsSpecified which you set to false if the attribute value false means null.

Can a boolean column be null?

Yep - it can be null. Your Boolean column is supposed to be only true or false . But now you're in the madness of three-state Booleans: it can be true , false , or NULL .

Can we assign null to boolean in C#?

We cannot assign null to int, bool, double, char values while retrieving values from the database. So it is recommended to use nullable types instead of value types in a case where we want to store the null value.


2 Answers

You need to use a nullable bool:

bool? b = null; 
like image 188
Jon Avatar answered Oct 11 '22 07:10

Jon


C# has two different categories of types: value types and reference types. Amongst other, more important distinctions, value types, such as bool or int, cannot contain null values.

You can, however, use nullable version of value types. bool? is a C# alias for the .NET Nullable<bool> type (in the same way string is an alias for String) and can contain null values.

like image 31
ICR Avatar answered Oct 11 '22 07:10

ICR