C# null

The null keyword is defined as a literal in C# and it represents a reference pointing to nowhere. It can be assigned to any reference-type variables and is also the default value of any reference-type fields.

Example 01-78-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;

class MyClass{}

class TestNull
{
    MyClass m1;
    string s1;
    int i;

    static void Main()
    {
        // Test 1: Default values of reference types
        TestNull tn = new TestNull();
        if (tn.s1 == null && tn.m1 == null)
        {
            Console.WriteLine("Test1: null");
        }
        else
        {
            Console.WriteLine("Test1: not null");
        }

        // Test 2: Default values of Local variables
        MyClass m2;
        m2 = null;      // What will be happened if this line is commented out.
        if (m2 == null)
        {
            Console.WriteLine("Test2: null");
        }
        else
        {
            Console.WriteLine("Test2: not null");
        }
        
        // Test 3: null == "" ? for string
        string s2 = "";
        if (s2 == null)
        {
            Console.WriteLine("Test3: equal");
        }
        else
        {
            Console.WriteLine("Test3: not equal");
        }

        // Test 4: null == null
        if (null == null)
        {
            Console.WriteLine("Test4: equal");
        }
        else
        {
            Console.WriteLine("Test4: not equal");
        }

        Console.Read();
    }
}

Output

Test1: null
Test2: null
Test3: not equal
Test4: equal

Explanation

  • Line 14-22: Instantiate the class TestNull and testing if the default fields m1 and s1 are null by default. The result is YES. string is a reference type so the default value of a string field is null. The default value of i is 0.
  • Line 25-34: m2 is a local variable of the MyClass and it is null because it is assigned as null. If the code in line 26 is commented out, you will get a compile-time error because m2 has never been assigned any value including null. null is not an unsigned value.
  • Line 37-45: These codes prove the empty string is not null.
  • Line 48-55: We prove null is null. But in database, NULL is not NULL. See the following screen shot. These are 2 SQL statements and their results. As you can see, it returns nothing because NULL = NULL and NULL <> NULL all return false.
  • NULL is not NULL in SQL