Catch NullReferenceException Exception : Object Instance « Class Interface « C# / C Sharp






Catch NullReferenceException Exception


using System;

class MyClass {
    public int Value;
}

class MainClass {
    public static void Main() {
        try {
            MyClass MyObject = new MyClass();
            MyObject = null;

            MyObject.Value = 123;

        } catch (NullReferenceException) {
            Console.WriteLine("Cannot reference a null object.");
        }
    }
}

           
       








Related examples in the same category

1.Object.ReferenceEquals Method
2.Calling an Instance Method on an Object
3.Calling a Class Method on a Class
4.Object assignment
5.Point object
6.Pass by ref for object parameters