C# - Nullable syntax

System.Nullable is a generic value type. It is implemented as a struct that holds an instance of the specified value type, along with a flag to indicate it's validity.


How to create:

(The process of creating a non-null instance of a nullable type from a given value is called wrapping).


  // T? is shorthand for System.Nullable<T>
  int? val = 10;
 
  // Every nullable type T? has a corresponding public constructor that takes a single argument of type T.
  var val = new int?(10);
 

How to test:


  // These are equivalent
  var hasValue1 = val != null;
  var hasValue2 = val.HasValue;
  

How to read:

(The process of accessing the Value property of a nullable type is called unwrapping).


  int i1 = (int)val;                  // Returns val.Value or throws a System.InvalidOperationException
  int i2 = val.Value;                 // Returns val.Value or throws a System.InvalidOperationException
  int i3 = val.GetValueOrDefault();   // Returns val.Value or zero
  int i4 = val.GetValueOrDefault(-1); // Returns val.Value or -1
  
  // Using the null-coalescing operator
  int i5 = val ?? -1;                 // Returns val.Value or -1
  

Ads by Google

Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath