Use the NullReferenceException

image_pdfimage_print

   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Use the NullReferenceException. 
 
using System;  
  
class X { 
  int x; 
  public X(int a) { 
    x = a; 
  } 
 
  public int add(X o) { 
    return x + o.x; 
  } 
} 
   
// Demonstrate NullReferenceException. 
public class NREDemo {   
  public static void Main() {   
    X p = new X(10); 
    X q = null; // q is explicitly assigned null 
    int val; 
 
    try { 
      val = p.add(q); // this will lead to an exception 
    } catch (NullReferenceException) { 
      Console.WriteLine("NullReferenceException!"); 
      Console.WriteLine("fixing...
"); 
 
      // now, fix it 
      q = new X(9);   
      val = p.add(q); 
    } 
 
    Console.WriteLine("val is {0}", val); 
  
  }  
}