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 [Last updated : March 08, 2023]

VB.Net – NullReferenceException

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 to fix NullReferenceException

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#.Net code to fix NullReferenceException

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!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.