Search code examples
vb.netclassextend

vb.net is it possible to extend a system class?


I want to add a function to System.IO.Path Class.

The Problem is Path is NotInheritable.

So doing that is impossible:

Imports System.IO

Public Class Path : Inherits System.IO.Path

End Class

Solution

  • You can use Extension Methods. Those seem to be the functions of the extended class, but there is no real connection between them. They do make programming a bit more convenient though.
    http://msdn.microsoft.com/en-us/library/bb384936.aspx

    Update: Let's see an example. Note that these are snippets from 3 files.

    'Noninheritable baseclass
    Public NotInheritable Class BaseClass
        Function f()
            Return 42
        End Function
    End Class
    
    'Extension
    Imports System.Runtime.CompilerServices
    Module ExtModule
        <Extension()>
        Public Sub Print(ByVal bc As BaseClass)
            Console.WriteLine(bc.f())
        End Sub
    End Module
    
    'Usage
    Sub Main()
        Dim bc As BaseClass
        bc = New BaseClass()
        bc.Print() 'Calling the extension method
    End Sub
    

    And it says 42.