Search code examples
.netvb.netobjectextension-methodslate-binding

VB.NET: impossible to use Extension method on System.Object instance


Can I make an Extension method for all the subclasses of System.Object (everything)?

Example:

<Extension>
Public Function MyExtension(value As Object) As Object
    Return value
End Function

The above functions won't work for object instance:

Dim myObj1 As New Object()
Dim myObj2 = myObj1.MyExtension()

The compiler does not accept it, is the problem in my computer? :)

UPDATE
The problem seems to occur only in VB, where members of object are looked-up by reflection (late-bound).

UPDATE AFTER ANSWERED
FYI, as vb has an advantage that C# lacks that is, members of imported Modules are imported to the global scope so you can still use this functions without their wrapper:

Dim myObj2 = MyExtension(myObj1)

Solution

  • You can not directly write an extension method for Object, but using generics you can achieve the same result:

    <Extension()>
    Public Function NullSafeToString(Of T)(this As T) As String
        If this is Nothing Then
           Return String.Empty
        End If
        Return this.ToString()
    End Function
    

    Note that you can call this as an extension method on everything except things that are declared to have the type Object. For those, you have to either call it directly (full proof) or call via casting (which could fail, as there is no univesal interface, so somewhat chancy).