C# NullReferenceException


NullReferenceException occurs when you try to to access member fields, or function types that points to null.

Here is an example −

Example

 Live Demo

using System;

class Demo {
   static void Main() {
      string str = null;

      if (str.Length > 0) {
         Console.WriteLine(str);
      }
   }
}

Output

The following is the output. It throws NullReferenceException, since you are tryonhg access a memebt that points to null −

Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object
at Demo.Main () [0x00002] in <0bc5fbf292484d5194a19866ae5c2018>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
at Demo.Main () [0x00002] in <0bc5fbf292484d5194a19866ae5c2018>:0

Updated on: 22-Jun-2020

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements