1

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 ?

MistyD
  • 16,373
  • 40
  • 138
  • 240
  • 1
    `Also how do I test if val_b is nullable` Do you want to know if it is `null` or `nullable`? They are two very different things. – mjwills Mar 23 '20 at 00:00
  • 1
    Does this answer your question? [Nullable vs. int? - Is there any difference?](https://stackoverflow.com/questions/4028830/nullableint-vs-int-is-there-any-difference) – devNull Mar 23 '20 at 00:00

2 Answers2

1

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);
Ankit Vijay
  • 3,752
  • 4
  • 30
  • 53
1

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.

Zer0
  • 7,191
  • 1
  • 20
  • 34