Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does this extension method throw a NullReferenceException in VB.NET?
    primarykey
    data
    text
    <p>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:</p> <pre><code>// code in static class static bool IsNull(this object obj) { return obj == null; } // code elsewhere object x = null; bool exists = !x.IsNull(); </code></pre> <p>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 <em>thought</em> was the VB.NET equivalent of the above code, only to discover that it actually throws a <code>NullReferenceException</code>. The code I wrote was this:</p> <pre><code>' code in module ' &lt;Extension()&gt; _ 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() </code></pre> <p>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 <strong>not</strong> 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.)</p> <p>Can anybody explain this one to me?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload