VB.NET Object Extension Method Problems RRS feed

  • Question

  • I'm trying to create an extension method that takes any object. It's irrelevant what I want it to do. The problem is that I can't get Extension Methods that take objects to work correctly in VB.NET. I don't have any problems with doing this in C#.

    I really think this is a compiler bug.  I've created a blog entry with screenshots and detailed information.!EBA860160D5F5D75!463.entry

    Can you confirm this is a bug/tell me a better place to post this/confirm that I'm an idiot Wink?

    Thursday, May 15, 2008 5:38 PM


All replies

  • I would try to ask your question on VB forums:

    This forum is related to .NET in general and VB experts might not be watching the threads here.


    I can reproduce the same issue. When you look at the IL generated by VB compiler, you can see that call to String's extension method is correct, however call to Object's extension method is translated as late-bound call, therefore it fails.

    I am not expert on VB, so I don't know if the generated late-bind call is accoring to specification of VB language or if it is a bug in the VB compiler. Try to ask on the VB language forum.


    Here's your example in copy-pastable form:

    Code Snippet

    Imports System.Runtime.CompilerServices


    Module MyModule

    <Extension()> _

    Public Function TestObjectExtension(ByVal obj As Object) As Object

    System.Console.WriteLine("TestObjectExtension called")

    Return obj

    End Function


    <Extension()> _

    Public Function TestStringExtension(ByVal obj As String) As Object

    System.Console.WriteLine("TestStringExtension called")

    Return obj

    End Function


    Public Class ExampleClass

    Public Shared Sub Main()

    Dim o As New Object

    Dim s As String = "My test"




    End Sub

    End Class

    End Module



    Thursday, May 15, 2008 8:41 PM
  • A little bit of search on the VB forums and here's the answer (


    VB allows you to *define* extension methods on Object, however they can't be *called* on Object.  The reason is that VB supports late-binding, and there wouldn't really be a good way to distinguish between a late-bound call or an in-scope extension method.


    For a more in-depth explanation, I'd recommend Scott Wisniewski's excellent series on extension methods (specifically Part 4) at



    Thursday, May 15, 2008 8:47 PM