Click here to Skip to main content
15,895,777 members
Articles / Programming Languages / Visual Basic

A Beginner's Guide to Delegates

Rate me:
Please Sign up or sign in to vote.
4.65/5 (89 votes)
29 Mar 20064 min read 515.3K   6.9K   177  
An article on delegates in .NET.
Module MulticastDelegates

    Public Delegate Sub GreetingDelegate(ByVal MsgString As String)

    Public Sub GoodMorning(ByVal YourName As String)
        Console.WriteLine("Good Morning " + YourName + " !")
    End Sub

    Public Sub GoodNight(ByVal YourName As String)
        Console.WriteLine("Good Night " + YourName + " !")
    End Sub

    Public Sub GoodEvening(ByVal YourName As String)
        Console.WriteLine("Good Evening " + YourName + " !")
    End Sub

    Sub Main()
        Dim MorningGreets As GreetingDelegate = AddressOf GoodMorning
        Dim EveningGreets As GreetingDelegate

        'MorningGreets()
        EveningGreets = New GreetingDelegate(AddressOf GoodEvening)

        Console.WriteLine()
        Console.WriteLine("Adding 'MoringGreets' And 'EveningGreets' References To A Delegate...")
        Dim AllGreets As GreetingDelegate = [Delegate].Combine(MorningGreets, EveningGreets)

        Console.WriteLine("Invoking Delegate...")
        AllGreets("Mallinath")

        Console.WriteLine()
        Console.WriteLine("Adding Another References To Existing Delegate...")
        AllGreets = [Delegate].Combine(AllGreets, New GreetingDelegate(AddressOf GoodNight))

        Console.WriteLine("Invoking Delegate...")
        AllGreets("Mallinath")

        Console.WriteLine()
        Console.WriteLine("Removing 'GoodEvening' Regerence...")
        Console.WriteLine("Invoking Delegate After Removing A 'GoodEvening'...")
        AllGreets = [Delegate].Remove(AllGreets, EveningGreets)
        AllGreets("Mallinath")

        Console.WriteLine()

    End Sub

End Module

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer
India India
Hello All !
This is Mallinath S. Karkanti, from India. I'm working as a Software Developer in one of the Middle Scale Company... !

Comments and Discussions