What is the difference between these two
public Nullable<bool> val_a { get; set; }
public bool? val_b { get; set; }
These are both Nullable type.
Also how do I test if val_b is nullable in one line ?
What is the difference between these two
public Nullable<bool> val_a { get; set; }
public bool? val_b { get; set; }
These are both Nullable type.
Also how do I test if val_b is nullable in one line ?
bool? is a short-hand notation for Nullable<bool>. They are same.
From the docs:
Any nullable value type is an instance of the generic System.Nullable structure. You can refer to a nullable value type with an underlying type T in any of the following interchangeable forms: Nullable<T> or T?.
To test if val_b is null, simply check val_b.HasValue. For example:
if (val_b.HasValue)
{
var b = val_b.Value;
}
You can also do something like:
var b = val_b.GetValueOrDefault();
or
var b = val_b ?? false;
In case of bool the default would be false.
To override the default value to true, you can use GetValueOrDefault overload:
var b = val_b.GetValueOrDefault(true);
Those are the same thing. Just like using Int32 or int. No difference.
Testing nullable bools is straight forward but there's a catch.
Common tests like if (val_a) and if (!val_a) don't work because a nullable bool has three states: true, false and null.
These work because you're doing an explicit comparison:
if (val_a == true)
if (val_a == false)
if (val_a == null)
You can also use the null coalescing operator if you wish, though this is more useful for other nullable types:
if (val_a ?? false)
See here if you want to test if a given type is nullable.