One of the most powerful feature of delegates is Multicasting , It is the feature using which a delegate can create an invocation chain. This is a list of method that are automatically called when a delegate is invoked.
To add methods to the chain, += or += is used .
To remove methods from the chain - or -= is used.
If a delegates returns a value, the value by the last method in the chain becomes the value returned by entire delegate invocation, hence usually the method in the chain have void return type.
Delegate Console Application Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegatesmulticasting
{
delegate void Intops(int a, int b);
class Program
{
public void add(int a, int b)
{ Console.WriteLine("Addition-"+(a + b)); }
public void sub(int a, int b)
{ Console.WriteLine("substraction-" + (a - b)); }
public void div(int a, int b)
{ Console.WriteLine("division-" + (a / b)); }
public void mul(int a, int b)
{ Console.WriteLine("Multiplication-" + (a * b)); }
static void Main(string[] args)
{
int a, b;
Intops intop;
Program p = new Program();
Console.WriteLine("\n Enter 2 integer");
Console.Write("a-");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("b-");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("b-");
intop = p.add;
intop += p.sub;
intop += p.div;
intop += p.mul;
intop(a,b);
Console.ReadLine();
}
}
}
Output:
To add methods to the chain, += or += is used .
To remove methods from the chain - or -= is used.
If a delegates returns a value, the value by the last method in the chain becomes the value returned by entire delegate invocation, hence usually the method in the chain have void return type.
Delegate Console Application Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegatesmulticasting
{
delegate void Intops(int a, int b);
class Program
{
public void add(int a, int b)
{ Console.WriteLine("Addition-"+(a + b)); }
public void sub(int a, int b)
{ Console.WriteLine("substraction-" + (a - b)); }
public void div(int a, int b)
{ Console.WriteLine("division-" + (a / b)); }
public void mul(int a, int b)
{ Console.WriteLine("Multiplication-" + (a * b)); }
static void Main(string[] args)
{
int a, b;
Intops intop;
Program p = new Program();
Console.WriteLine("\n Enter 2 integer");
Console.Write("a-");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("b-");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("b-");
intop = p.add;
intop += p.sub;
intop += p.div;
intop += p.mul;
intop(a,b);
Console.ReadLine();
}
}
}
Output:
No comments:
Post a Comment