How to create extension method to add method to an existing class in VB.NET

3 Answers

0 votes
Imports System.Runtime.CompilerServices

Module Module1

    Sub Main()

        Dim s1 As String = "obi-wan kenobi"
        Dim s2 As String = "vb programming language"

        s1.Print()
        s2.Print()

    End Sub

    ' Extension Method
    <Extension()>
    Sub Print(s As String)

        Console.WriteLine(s)

    End Sub

End Module

' run:
' 
' Obi-wan kenobi
' Vb programming language

 



answered Jan 25, 2017 by avibootz
0 votes
Imports System.Runtime.CompilerServices

Module Module1

    Sub Main()

        Dim n As Integer = 13
        Dim r As Integer

        r = n.Multiply(10)
        Console.WriteLine(r)

        r = n.Multiply(10).Multiply(3)
        Console.WriteLine(r)

    End Sub

    ' Extension Method
    <Extension()>
    Function Multiply(n As Integer, mulitiplier As Integer) As Integer

        Return n * mulitiplier

    End Function

End Module

' run:
' 
' 130
' 390

 



answered Jan 25, 2017 by avibootz
0 votes
Imports System.Runtime.CompilerServices

Module Module1

    Sub Main()

        Dim n As Integer = 13
        Dim r As Integer

        r = n.Multiply(10)
        r.Print()

        r = n.Multiply(10).Multiply(3)
        r.Print()

        n.Multiply(10).Print()


    End Sub

    ' Extension Method
    <Extension()>
    Function Multiply(n As Integer, mulitiplier As Integer) As Integer

        Return n * mulitiplier

    End Function

    <Extension()>
    Sub Print(s As Integer)

        Console.WriteLine(s)

    End Sub

End Module

' run:
' 
' 130
' 390
' 130

 



answered Jan 25, 2017 by avibootz
...