C# Language Keywords null

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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 + "!");
    }
}


Got any C# Language Question?