Home
C#
null String Example
Updated Aug 5, 2021
Dot Net Perls
Null strings. We often deal with null or uninitialized string references. In C# programs, null strings are a common cause of exceptions.
null
Nullable
Strings are initialized to null automatically at the class level, but we must assign them in methods. One popular method for dealing with null strings is the string.IsNullOrEmpty method.
string.IsNullOrEmpty
Example. All class-level reference variables are initialized to null. Strings are reference types—the variable points to an object on the heap that contains that data.
object
Start This example shows that when a class-level variable is used in any method, it is null if it has not been initialized yet.
Note The compiler allows the code to be executed. This is a pattern that many programs use.
Info A compile-time error will occur if you not assign the string. This is called definite assignment analysis.
Tip The example shows that you can use unassigned member variable strings, but not unassigned local variable strings.
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) { } */ } }
String is null
Length. One common problem with null strings is trying to take their lengths with the Length property. This will cause a NullReferenceException.
String Length
System.NullReferenceException: Object reference not set to an instance of an object.
Summary. We saw how null strings are initialized at the class level, and how to definitely assign them in the local variable declaration space. And we reviewed some common null errors.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 5, 2021 (edit).
Home
Changes
© 2007-2025 Sam Allen