TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Null Tips

This C# example set explores the null literal. Null is not the same as zero.

Null points to no object.

Here we see some information and facts about the null literal ("null"). Null is represented by the value 0, but you cannot use 0 instead of null in your programs.

Null causes lots of exceptions.

Exception

Example. This program assigns an object reference to the null literal. You can use null with any reference type. This includes strings, arrays, and more unique types such as StringBuilder or custom types.

Also: This program shows how the intermediate language represents the null literal (with ldnull).

C# program that assigns reference to null

using System;

class Program
{
    static void Main()
    {
	object value = new object();
	value = null;
	Console.WriteLine(value);
    }
}

Intermediate language of the program: IL

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
	[0] object 'value')
    L_0000: newobj instance void [mscorlib]System.Object::.ctor()
    L_0005: stloc.0
    L_0006: ldnull
    L_0007: stloc.0
    L_0008: ldloc.0
    L_0009: call void [mscorlib]System.Console::WriteLine(object)
    L_000e: ret
}

Discussion. In the C# language, null is not the same thing as the constant zero. The C# compiler makes sure the two values are not used in inappropriate contexts. In the IL language, null is also kept separate.

However: Null is equal to zero at the machine level according to page 285 of Expert .NET 2.0 IL Assembler.

Also, what happens when you assign a reference to the null literal? There is no null object allocation. Instead, the value zero is copied to the reference. In the C# language, all assignments are simple bitwise copies.

Tip: Assignments are extremely fast to execute. They need no custom optimization.

Arrays. These example programs show how 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.

Next: We show a program that checks the array against the null literal and avoids the exception.

Null ArrayNullReferenceException

C# program that assigns null to array

using System;

class Program
{
    static void Main()
    {
	string[] array = { "a", "b", "c" };
	array = null;
	int value = array.Length;
	Console.WriteLine(value);
    }
}

Result
   (Output was truncated.)

Unhandled Exception: System.NullReferenceException:
   Object reference not set to an instance of an object.
   at Program.Main() in C:\Users\...\Program.cs:line 9

Corrected program that assigns null to array: C#

using System;

class Program
{
    static void Main()
    {
	string[] array = { "a", "b", "c" };
	array = null;
	if (array != null)
	{
	    int value = array.Length;
	    Console.WriteLine(value);
	}
    }
}

Result
    (It doesn't crash.)

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 string.IsNullOrWhiteSpace. We can also just check against the null literal.

IsNullOrEmptyIsNullOrWhiteSpaceNull Strings

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

Summary. Is nothing something? Does nothing exist? These questions are hard to answer. Null is an important concept to grasp in imperative languages. We discovered some neat low-level machine details about null.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf