Users Online

· Guests Online: 144

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C# Program to Combine Two Delegates

C# Program to Combine Two Delegates

 

 

This is a C# Program to combine two delegates.

Problem Description

This C# Program Combines Two Delegates.

Problem Solution

Here when the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same type can be combined.

Program/Source Code

Here is source code of the C# Program to Combine Two Delegates. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Combine Two Delegates
 */
using System;
delegate void dele(string s);
class TestClass
{ 
    static void Good(string s)
    {
        System.Console.WriteLine("  Good, {0}!", s);
    }
 
    static void Morning(string s)
    {
        System.Console.WriteLine("  Morning, {0}!", s);
    }
 
    static void Main()
    {
        dele firstdel, secondDel, multiDel, multiMinusfirstdel;
        firstdel = Good;
        secondDel = Morning; 
        multiDel = firstdel + secondDel;
        multiMinusfirstdel = multiDel - firstdel;
        Console.WriteLine("Invoking delegate firstdel:");
        firstdel("A");
        Console.WriteLine("Invoking delegate secondDel:");
        secondDel("B");
        Console.WriteLine("Invoking delegate multiDel:");
        multiDel("C");
        Console.WriteLine("Invoking delegate multiMinusfirstdel:");
        multiMinusfirstdel("D");
        Console.ReadLine();
    }
}
Program Explanation

This C# program is used to combine two delegates. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

 

Assign good to the firstdel variable and morning secondDel variable. Delegate objects can be composed using the “+” operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed.

 

Using this property of delegates, create an invocation list of methods that will be called when a delegate is invoked.This is called multicasting of a delegate. Here when the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same type can be combined.

Runtime Test Cases
 
Invoking delegate firstDel:
  Good, A!
Invoking delegate SecondDel:
  Morning, B!
Invoking delegate multiDel:
  Good, C!
  Morning, C!
Invoking delegate multiMinusFirstDel:
  Morning, D!

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.14 seconds
10,815,884 unique visits