Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this extension method throw a NullReferenceException in VB.NET?

Tags:

People also ask

What does system NullReferenceException mean?

A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.

How can we avoid system NullReferenceException object reference not set to an instance of an object?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

Should I throw NullReferenceException?

You should never throw a NullReferenceException manually. It should only ever be thrown by the framework itself. From the NullReferenceException documentation: Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.

Can extension method null?

Extension methods are static methods which behave like instance methods. However, unlike what happens when calling an instance method on a null reference, when an extension method is called with a null reference, it does not throw a NullReferenceException . This can be quite useful in some scenarios.


From previous experience I had been under the impression that it's perfectly legal (though perhaps not advisable) to call extension methods on a null instance. So in C#, this code compiles and runs:

// code in static class static bool IsNull(this object obj) {     return obj == null; }  // code elsewhere object x = null; bool exists = !x.IsNull(); 

However, I was just putting together a little suite of example code for the other members of my development team (we just upgraded to .NET 3.5 and I've been assigned the task of getting the team up to speed on some of the new features available to us), and I wrote what I thought was the VB.NET equivalent of the above code, only to discover that it actually throws a NullReferenceException. The code I wrote was this:

' code in module ' <Extension()> _ Function IsNull(ByVal obj As Object) As Boolean     Return obj Is Nothing End Function  ' code elsewhere ' Dim exampleObject As Object = Nothing Dim exists As Boolean = Not exampleObject.IsNull() 

The debugger stops right there, as if I'd called an instance method. Am I doing something wrong (e.g., is there some subtle difference in the way I defined the extension method between C# and VB.NET)? Is it actually not legal to call an extension method on a null instance in VB.NET, though it's legal in C#? (I would have thought this was a .NET thing as opposed to a language-specific thing, but perhaps I was wrong.)

Can anybody explain this one to me?