0
votes

I have a column DBIsValid of type bit which is nullable.

I have a variable IsValid of type bool which I want to set as True if the DBIsvalid is True. Should my below line of code work fine or should I be checking for NULLs.

bool IsValid = this.DBIsValid.Value

Basically will DBIsValid return false if it is NULL in DB?

4
You haven't mentioned how you select the value from the database. The problem is not clear. What is DBIsValid at all?Tim Schmelter

4 Answers

7
votes

You should use HasValue property, if the value is null accessing .Value will throw an exception.

Another safer way to get value is using GetValueOrDefault

bool IsValid = this.DBIsValid.GetValueOrDefault();
1
votes

If it's nullable, you'll receive a null (which is neither true nor false).

When referencing any kind of Nullable<T> though, you should be checking HasValue. Alternatively, if you have a desired value when there is a null, you can use GetValueOrDefault.

// Value coming from database
Boolean? db_IsValid = null;

// Option 1:
// Check for null
Boolean IsValid = db_IsValue.HasValue ? db_IsNull.Value : false;

// Option 2:
// Using GetValueOrDefault
Boolean IsValid = db_IsValid.GetValueOrDefault(/*optional: false*/);
// note above, without parameter, returns default(Boolean)

// Option 3:
// Syntactical sugar (producing same output as Option 1 or 2)
Boolean IsValid = IsValid ?? false;
1
votes

No, It has three states: true, false and null, null meaning no value.

If you access this.DBIsValid.Value when this.DBIsValid is null an exception will be thrown.

In the case you want to give the null value a meaning of false, you have to test any of the following:

bool IsValid = this.DBIsValid ??  false; // commom pattern for a default
bool IsValid = this.DBIsValid.GetValueOrDefault(); // works because false is the default value for booleans
bool IsValid = this.DBIsValid.HasValue && this.DBIsValid.Value; // interprets no value as false
0
votes

Use the null coalescing operator ?? as shown below

bool IsValid = this.DBIsValid ?? false