...

/

Null Value

Null Value

Learn what the null value is.

The null and reference types

In C#, we have a special value called null. This value represents the absence of value and is the default for reference-type variables.

string name = null;

The null value means that a variable doesn’t point to anything in memory. Because we’re dealing with references, we can’t assign null to a value-type variable, such as int.

If we try to access a variable that doesn’t point to anything, we get a NullReferenceException:

Press + to interact
using System;
namespace NullValue
{
class Program
{
static void Main(string[] args)
{
string name = null;
// name is null. Accessing its members and methods
// will yield an error
string nameInUpperCase = name.ToUpper();
Console.WriteLine(nameInUpperCase);
}
}
}

The null and value types

Unlike reference types, value-type variables can’t be assigned the null value directly. However, it’s quite common to potentially need a value-type to be null. For instance, if we’re fetching some ...