C#. The value of null. Nullable data types




The value of null. Nullable data types. Operations ?, ??


Contents


Search other websites:

1. The value of null. Assignment

The null value is used to represent an empty reference to an object. This value can be assigned to variables of reference types.

Example.

The example shows the assignment of null values to references to objects of the CMyClass and string classes. If you try to assign a null value to an int variable, the compiler will give an error message.

class CMyClass
{
  public int value;
}

class Program
{
  static void Main(string[] args)
  {
    CMyClass obj;
    obj = null; // empty reference to an object of class CMyClass

    string s = null; // null reference to a string

    // int d = null; - error: int type is not null type
    Console.ReadKey();
  }
}

 

2. Syntax of null data type. Suffix ?

In the C# programming language, all basic numeric data types (int, float, double, bool, and others) are value types. These types can never be set to null. The value of null can be assigned to variables of reference types such as classes.

There are cases when you want a value type to be null. For example, in database tables, under certain conditions, there may be fields that contain undefined null values.

In order for the value type to support null, C# uses the following general form, which contains the character ?.

type? variable;

where

  • type – value type, which should allow the null value;
  • variable – the name of the variable to which null can be assigned.

 

3. Examples of using null values in variables of base types

 

...

// Nullable-types

// This is error
// int d = null; // error - d is not a Nullable-type

// It works
int? d2 = null;

double? x;
x = 25;
x = null;

bool? b;
b = true;
b = null;

float? f;
f = null;

...


 

4. Sufix ? and structure System.Nullable<T>. The purpose. Example

If the compiler after the type name encounters the suffix ?, then it creates an instance of the generic structure System.Nullable<T>.

The System.Nullable<T> structure provides an additional set of tools that work with nullable types. These tools include:

  • property HasValue. This property determines whether the current object of type System.Nullable<T> has a persistent value of type T (here, instead of type T, any base type is int, double, etc.). The property returns true if the current object has such a value; otherwise, false is returned (see the example below). In other words, the HasValue property returns false if the value of the object is null;
  • property Value – returns the current value that is assigned to a variable of type that allows null;
  • method GetValueOrDefault(). If the Nullable variable is not null, then this method returns this value. If the Nullable variable is null, then the method returns the default value (usually 0). This method must be used to correctly assign a value from a Nullable type to a regular base type.

Example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // 1. Declaring a variable of type System.Nullable<int>
      System.Nullable<int> d; // could be like this: int? d;

      // 2. Declaring a variable of type System.Nullable<double>
      double? t = null;

      // 3. Свойство Value - demonstration of the correct assignment
      // type int?
      d = null;
      int d2; // it is not Nullable-type

      if (d == null)
        d2 = 0;
      else
        d2 = d.Value; // d2 = 335

      // type double?
      t = -10.55;
      double t2;
      if (t != null)
        t2 = t.Value; // t2 = -10.55
      else
        t2 = 0.0;

      // 4. Property HasValue
      // Checking, is the variable t equal to null
      t = null;
      if (t.HasValue)
        Console.WriteLine("t != null");
      else
        Console.WriteLine("t == null");

      // 5. Method GetValueOrDefault() - You do not need to do the checking for null
      t = null;
      double t3 = t.GetValueOrDefault(); // t3 = 0 - default value

      Console.WriteLine("d2 = {0}", d2);
      Console.WriteLine("t2 = {0}", t2);
      Console.WriteLine("t3 = {0}", t3);

      Console.ReadKey();
    }
  }
}

The result of the program

t == null
d2 = 0
t2 = -10.55
t3 = 0

 

5. How to programmatically determine if a null value has been assigned to a nullable variable?

If the variable is null, then you can determine whether this variable contains null in the following ways:

  • use one of the operations == or !=;
  • use the HasValue property.

Example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // Checking if a null value has been assigned to a nullable variable
      char? symbol; // some Nullable-variable

      // Way 1. Operation ==
      symbol = null;
      if (symbol == null)
        Console.WriteLine("symbol == null");
      else
        Console.WriteLine("symbol != null");

      // Way 2. Operation !=
      symbol = 'a';
      if (symbol != null)
        Console.WriteLine("symbol != null");
      else
        Console.WriteLine("symbol == null");

      // Way 3. Property HasValue
      symbol = null;
      if (symbol.HasValue)
        Console.WriteLine("symbol != null");
      else
        Console.WriteLine("symbol == null");

      Console.ReadKey();
    }
  }
}

The result of the program

symbol == null
symbol != null
symbol == null

 

6. Operation ?? (null-coalescing). The purpose. Example

Operation ?? allows you to set a Nullable-type object to a specified value if the value of this object is null. The operation allows you to replace program code that uses the if-else statement. By comparing if-else, this operation is more compact.

Example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
  class Program
  {
    static void Main(string[] args)
    {
      // Operation ??
      uint? d; // some Nullable-type
      uint? t;

      d = null;
      t = d ?? 50; // t = 50
      Console.WriteLine("t = {0}", t);

      d = 20;
      t = d ?? 50; // t = 20
      Console.WriteLine("t = {0}", t);

      Console.ReadKey();
    }
  }
}

The result of the program

t = 50
t = 20

 


Related topics