C# Null String Usage

Null keyword

Null strings present difficulties. You are dealing with null or uninitialized string references in your C# program. Strings are initialized to null automatically at the class level, but you must assign them in methods. We look at some of the complexities of null strings.

This C# article provides some facts about null strings. It shows how you can avoid errors.

Example

Programming tip

First, in the C# programming language, all class-level instance variables, as well as static type members, are initialized to null if they are reference variables. Strings in C# are reference types, meaning they do not contain the character values in the variable, but that the variable points to an object on the heap that contains that data.

Null Tips
Program that uses null string [C#]

using System;

class Program
{
    static string _test1;

    static void Main()
    {
	// Instance strings are initialized to null.
	if (_test1 == null)
	{
	    Console.WriteLine("String is null");
	}

	string test2;

	// // Use of unassigned local variable 'test2'
	// if (test2 == null)
	// {
	// }
    }
}

Output

String is null

Notes. This example shows that when a class-level variable (static and also not static) is used in any method, it is null if it has not been initialized yet. The compiler will allow the code to be executed. This is a pattern that many programs use.

Method call

Null strings in methods. The commented-out part of the above example shows that a compile-time error will occur if you not assign the string to the null literal when used in the method. This process is called definite assignment analysis and it prevents many errors. The example shows that you can use unassigned member variable strings, but not unassigned local variable strings.

Definite Assignment Analysis

Null string length

Warning

One common problem with null strings is trying to take their lengths with the Length property. This will cause a NullReferenceException. The article on the string Length property on this site addresses this issue.

String Length Property

System.NullReferenceException: Object reference not set to an instance of an object.

Summary

We looked at how null strings are initialized at the class level, and how you must definitely assign them in the local variable declaration space. We saw some common errors and reviewed the fact that strings are a reference type, not a value type.

string.IsNullOrEmpty Method String Type
.NET