C# Language null


Example

A variable of a reference type can hold either a valid reference to an instance or a null reference. The null reference is the default value of reference type variables, as well as nullable value types.

null is the keyword that represents a null reference.

As an expression, it can be used to assign the null reference to variables of the aforementioned types:

object a = null;
string b = null;
int? c = null;
List<int> d  = null;

Non-nullable value types cannot be assigned a null reference. All the following assignments are invalid:

int a = null; 
float b = null;
decimal c = null;

The null reference should not be confused with valid instances of various types such as:

  • an empty list (new List<int>())
  • an empty string ("")
  • the number zero (0, 0f, 0m)
  • the null character ( '\0' )

Sometimes, it is meaningful to check if something is either null or an empty/default object. The System.String.IsNullOrEmpty(String) method may be used to check this, or you may implement your own equivalent method.

private void GreetUser(string userName)
{
    if (String.IsNullOrEmpty(userName))
    {
        //The method that called us either sent in an empty string, or they sent us a null reference. Either way, we need to report the problem.
        throw new InvalidOperationException("userName may not be null or empty.");
    }
    else
    {
        //userName is acceptable.
        Console.WriteLine("Hello, " + userName + "!");
    }
}