Delegate in c#
What is delegate in c#??
In this lesson we learn delegate.We know that structure are value type but classes and interfaces are reference type .Similarly Delgate is reference type.- A delegate is a funtion pointer.
- A delegate is type safety
- A delegate can be used to define callback methods.
Let us understand with Example.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public delegate void Hellofunctiondelegate(string message);
class Delegate
{
static void Main(string[] args)
{
//a delegate is a type safety function pointer
Hellofunctiondelegate del = new Hellofunctiondelegate(Hello);
del("hello world delegate");
}
public static void Hello(string strmessage)
{
Console.WriteLine(strmessage);
}
}
}
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public delegate void Hellofunctiondelegate(string message);
class Delegate
{
static void Main(string[] args)
{
//a delegate is a type safety function pointer
Hellofunctiondelegate del = new Hellofunctiondelegate(Hello);
del("hello world delegate");
}
public static void Hello(string strmessage)
{
Console.WriteLine(strmessage);
}
}
}
What is multicast Delegate??
There are two approaches to create a multicast delegate.Depending on the approach you use
+ or+= to register method with the delegate
-or-= to un-register a method with the delegate.
Note: A multicast delegate,invokes the methods in the invocation list,in the same order in which they are added.
If the delegate has a return type other than void and if the delegate is a multicast delegate
This means only the value of the last invoked method will be returned.Along the same lines,If the delegates has an out parameter,the value of the output parameter, will be the value assigned by the last method.
0 Comments