Net-informations.com
SiteMap  | About    

What is .Net Delegates

Delegates

In the .NET environment, a delegate is a type that defines a method signature and it can pass a function as a parameter. In simple words we can say delegate is a .NET object which points to a method that matches its specific signature. A delegate is a form of type-safe function pointer used by the Common Language Infrastructure.

delegates

You create a delegate with the delegate keyword, followed by a return type and the signature of the methods that can be delegated to it.

public delegate void delegateMethod(int n1, int n2);

A delegate is independent of the type of method that it references. The signature of the method and the delegate should match. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

//A class method public void add(int n1, int n2) { MessageBox.Show("Adding numbers : " + (n1 + n2).ToString()); } //invocaton Form1 form1 = new Form1(); delegateMethod addNumbers = new delegateMethod(form1.add); addNumbers(50, 10);

Delegates

There are two types of Delegates

1) Singlecast delegates

2) Multiplecast delegates

Singlecast delegate:

A Singlecast delegate point to single method at a time and it is derived from System.Delegate class.

Multicast Delegate:

A delegate that can have more than one element in its invocation list is known as a multicast delegate. When you create a Delegate object, you actually create an instance of an object that inherits the System.MulticastDelegate class. The MulticastDelegate class lets you assign multiple methods to a delegate.

The following examples shows how to implement delegates in .Net programs

C# Delegate

using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public delegate void delegateMethod(int n1, int n2); public void add(int n1, int n2) { MessageBox.Show("Adding numbers : " + (n1 + n2).ToString()); } private void button1_Click(object sender, EventArgs e) { Form1 form1 = new Form1(); delegateMethod addNumbers = new delegateMethod(form1.add); addNumbers(10, 20); } public Form1() { InitializeComponent(); } } }

VB.Net Delegate

Public Class Form1 Public Delegate Sub delegateMethod(ByVal n1 As Integer, ByVal n2 As Integer) Public Sub add(ByVal n1 As Integer, ByVal n2 As Integer) MessageBox.Show("Adding numbers : " + (n1 + n2).ToString()) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim form1 As New Form1() Dim addNumbers As New delegateMethod(AddressOf form1.add) addNumbers(10, 20) End Sub End Class




 Microsoft .Net Interview Questions - Related Contents