Home
C#
null Keyword
This page was last reviewed on Oct 4, 2024.
Dot Net Perls
Null. Used throughout C# programs, the null keyword means "no object." Here we see some information and facts about the null literal. There are some special rules with null in C#.
Null is represented by the value 0, but you cannot use 0 instead of null in your programs. Null causes lots of exceptions. We use if-statements to prevent these problems.
Nullable
Null Coalescing
Example. This program assigns an object reference to the null literal. You can use null with any reference type. This includes strings, arrays and custom types.
Info In C# programs, we often use "is equal to null" tests. An if-statement checks for null.
if
using System; // Create new object and assign it to null. object value = new object(); value = null; // Test to see if the variable is null. if (value == null) { Console.WriteLine("Is null"); }
Is null
Arrays. You can assign an array reference to the null literal. When you then try to access a property or method on that null reference, you get a NullReferenceException.
null Array
NullReferenceException
using System; // Create an array and then assign it to null. string[] array = { "a", "b", "c" }; array = null; // This will cause an exception! int value = array.Length; Console.WriteLine(value);
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. at Program.<Main>$(String[] args) in ...\Program.cs:line 8
Arrays, continued. We show a program that checks the array against the null literal and avoids the exception. The program completes without throwing an exception.
using System; // Create an array, and null to it. string[] array = { "a", "b", "c" }; array = null; // Ensure the array is not null before entering the block. if (array != null) { int value = array.Length; Console.WriteLine(value); } else { Console.WriteLine("OK"); }
OK
Strings. Because strings are a reference type, they too can be null. We often want to protect against null strings. We do this with string.IsNullOrEmpty or just the null literal.
null String
using System; // Use a null string, and the null coalescing operator to test it. string value = null; Console.WriteLine(value ?? "Is null");
Is null
Fields. Fields that are reference types are always initialized to null when the enclosing type is instantiated. We therefore never have to initialize fields to null in a class constructor.
class
using System; class Bird { public string _color; } class Program { public static void Main() { var bird = new Bird(); // The field was automatically initialized to null. Console.WriteLine(bird._color == null); } }
True
Null conditional. C# has some syntax features that make dealing with null easier. They use the question mark. Here we use the null conditional operator on a null, and a non-null variable.
using System; using System.Text; // Part 1: use null conditional operator on null variable. StringBuilder test = null; Console.WriteLine("RESULT1: {0}", test?.Length); // Part 2: use null conditional operator on non-null variable. StringBuilder test2 = new StringBuilder("cat"); Console.WriteLine("RESULT2: {0}", test2?.Length);
RESULT1: RESULT2: 3
Avoiding null. Some patterns encourage the elimination of the null value. We can use a "Null Object" that is not actually null, but has a similar logical result.
Part 1 Here we create an instance of a NormalObject, which prints a message on the Honk method.
Part 2 With a NullObject, we have a Honk implementation that does nothing—this class can be used to indicate there is no car instance.
Part 3 We can call Honk on the NullObject, and no exception occurs because the class instance is not actually null.
using System; interface ICar { public void Honk(); } class NormalObject : ICar { public void Honk() { Console.WriteLine("Honk"); } } class NullObject : ICar { void ICar.Honk() { // Do nothing on the null object. } } class Program { public static void Main() { // Part 1: we can use a non-null object. ICar temp = new NormalObject(); // Part 2: it may be necessary to use a special "null" object in some places. ICar temp2 = new NullObject(); // Part 3: Each object can be used in the same way. temp.Honk(); temp2.Honk(); } }
Honk
Summary. Null is a special value that means "no object." Null is an important concept in C-like languages, and is used throughout C# programs along with operators like the null coalescing operator.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 4, 2024 (new example).
Home
Changes
© 2007-2024 Sam Allen.