C# Nullable Types

C# included a types provides solution to common and irritating problem. Feature is nullable type.

The problem is lies with recognize and handle the fields that do not contain values for value types.
In past, unused fields required use of either placeholder values or extra field that simply indicated whether a field was in use. The nullable type solves both problems.

Nullable Basics

Nullable type is special version of value types that is represented by structure. In addition to values defined by underlying type, a nullable type can also store value null. Thus, nullable type has same range & characteristics as its underlying type. Simply adds ability to represent value that indicates that variable of that type is unassigned.

  • Nullable types are objects of System.Nullable, where T must be a non-nullable value type.

  • Nullable can be specified two different ways. First, explicitly declare objects of type Nullable.

    System.Nullable<int> count;

  • Second, declare nullable type shorter & commonly used way, simply type name & with ? Symbol.
    1. int? count;  
  • When using nullable types, you will often see a nullable object created like this:
    1. int? count = null;  
  • Determine if nullable contains value is either null or non-null to use HasValue read-only property defined by Nullable or test its value against null.
    1. if(count != null) Or if(count.HasValue)  

Nullable Objects in Expressions

  • Nullable object can be used in expressions that are valid for its underlying type.

  • Possible to mix Nullable and non-Nullable objects within same expression.

  • Works because of predefined conversion that exists from underlying type to nullable type.

  • When non-nullable & nullable types are mixed in an operation, outcome is nullable value.

The ?? Operator

Attempt to use cast to convert of Nullable object to underlying type, InvalidOperationException will be thrown if Nullable object contains a null value.

  • Occur, when cast to assign value of a Nullable object to a variable of its underlying type.

  • Avoid possibility of exception being thrown by using the ?? operator, which is called the null coalescing operator.

  • Specify default value that used when Nullable object contains null & eliminates need of cast.
    1. int? count = null;  
    2. int Currentcount;  
    3. Currentcount = count?? 0.0;  

Nullable Objects & Relational - Logical Operators

Nullable can be used in relational expressions just same way as their non-nullable types.
However, there is one additional rule that applies. When two Nullable objects are compared using logical operators, result is false if either of Nullable objects is null.

One other point: When the ! operator is applied to a bool ? value that is null, the outcome is null.

Ebook Download
View all
Learn
View all