C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program: We see how the intermediate language represents the null literal (with ldnull).
Info: Null is not the same thing as the constant zero. The compiler makes sure the two values are not used in inappropriate contexts.
IL: In the IL, null is also kept separate. Null is equal to 0 at the machine level according to Expert .NET 2.0 IL Assembler.
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
}
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);
}
}
Output
(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
C# program that assigns null to array, no exception
using System;
class Program
{
static void Main()
{
string[] array = { "a", "b", "c" };
array = null;
if (array != null)
{
int value = array.Length;
Console.WriteLine(value);
}
}
}
Output
(It doesn't crash.)
Assignments: In the C# language, all assignments are simple bitwise copies. No allocations occur.
Tip: Assignments are extremely fast to execute. They need no custom optimization.
Also: We can just check against the null literal. This approach is fastest if no length test is required.
Null Strings