VB.Net | What is a NullReferenceException, and how do I fix it?

Here, we are going to learn what is a NullReferenceException, and how do I fix it in VB.Net?
Submitted by Nidhi, on December 23, 2020

The NullReferenceException is a runtime error, which is generated by the block of code when we assign NULL (Nothing in VB.Net) to an object and access a member of the class.

The given code will print the below message on the console screen.

Object reference not set to an instance of an object.

VB.NET Code:

Class Sample
    Sub SayHello()
        Console.WriteLine("Hello World")
    End Sub
End Class

Module Module1
    Sub NonMemberFun(ByVal obj As Sample)
        obj.SayHello()
    End Sub
    
    Sub Main()
        Dim S As New Sample()
        Try
            S = Nothing
            S.SayHello()
        Catch ex As NullReferenceException
            Console.WriteLine(ex.Message)
        End Try
    End Sub
End Module

Output:

Object reference not set to an instance of an object

C# Code:

using System;

class Sample
{
    public void SayHello()
    {
        Console.WriteLine("Hello World");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Sample S = new Sample();

        try
        {
            S = null;
            S.SayHello();
        }
        catch (NullReferenceException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Output:

Object reference not set to an instance of an object

If we will instantiate the object of the class properly then NullReferenceException will not be generated.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.