C# Programming Language Null Reference Exception and Solution – POFTUT

C# Programming Language Null Reference Exception and Solution

Null Reference Exception is one of the most occurring exception. Object oriented languages generally creates new object for the variables. But if it is not created and not set by the developer trying to access an variable object will cause Null Reference Exception. In this examples we will use Csharp programming language for Null Reference Exception.

Raise Null Reference Exception

We can generate Null Reference Exception with the following example code. In this code we create a variable named name and set its value t null. If we try to run function ToUpper() which will return the name variable string in uppercase will create an Exception because there is no such value to use.

string name=null;


Another example can be a class or struct which is not set into an instance. This example will be similar to the previous example. We will create a variable ferrari which is a Car class type.

Car ferrari;


Solve Null Reference Exception

This code snippet will cause Null Reference Exception. To remove Null Reference Exception initialize the name object. We simply set some value different than null to prevent Null Reference Exception.

string name="This will not throw Null Reference Exception";


LEARN MORE  Python Standard Library

Leave a Comment