• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C# » Advanced » Delegates in C#
Next →
← Prev

Delegates in C#

By Dinesh Thakur

Delegate is a method template which used to implement the concept of function pointer.

 

The C and C++ languages are having the concept of function pointer. This was even more useful when programming for the Microsoft Windows operating systems because the Win32 library relies on the concept of callback functions. Callback functions are used in Microsoft Windows programming to process messages. For this reason and because of their functionality, callback functions were carried out in the .NET Framework but they were defined with the name of delegate.

~ Concept

A delegate is a special type of user-defined variable that is declared globally, like a class.

In fact, a delegate is created like an interface but as a method. Based on this, a delegate interface, a delegate is not defined. Its role is to show what a useful method would look like.To support this concept, a delegate can provide all the necessary information that would be used on a method. This includes a return type, no argument or one or more Argument.

We’ll be covering the following topics in this tutorial:

  • Delegate Declaration and Instantiation
  • Multicast Delegates
  • Delegates vs. Interface

Delegate Declaration and Instantiation

Delegates can be specified in their own namespace, or else can ‘be specified within other class. In each case, the declaration specifies a new class, which inherits from System.MulticastDelegate.

Each delegate is limited to referencing methods of a particular kind only. The type is indicated by the delegate declaration – the input parameters and return type given in the delegate declaration must be shared by the methods its delegate instances reference. To illustrate this: a delegate specified as below can be used to refer only to methods which have a single String input and no return value:

 

public delegate void print (String s);

 

Suppose, for instance, that a class contains the following method:

 

public void realMethod (String myString)

{

// method code

}

Another method in this class could then instantiate the ‘Print’ delegate in the following way, so that it holds a reference to ‘realMethod’:

 

print delegatevariable = new print(realMethod);

We can note two important points about this example. Firstly, the unqualified method passed to the delegate constructor is implicitly recognised as a method of the instance passing it. That is, the code is equivalent to:

 

Print delegatevariable = new print (this.realMethod);

We can, however, in the same way pass to the delegate constructor the methods of other class instances, or even static class methods. In the case of the former, the instance must exist at the time the method reference is passed. In the case of the latter (exemplified below), the class need never be instantiated.

 

Print delegatevariable = new

print(ExampleClass.exampleMethod);

 

Use of delegate

 

using System;

//delegate declaration

delegate int operation(int x, int y);

class MathOpr

{

public static int Add(int a,

{

return(a + b); }

public static int Sub(int a,

{

return( a – b); }

public static int Mul(int a,

{

return( a * b);

}

}

class Test

{

public static void Main () {

}

//delegate instances

operation opr1 = new operation (Mathopr.Add);

operation opr2 = new operation (Mathopr.sub);

operation opr3 = new operation (Mathopr.Mul);

 

//invoking of delegates

int ans1 = opr1(200, 100);

int ans2 = opr2(200, 100);

int ans3 = opr3(20,10);

 

Console.writeLine(“\n Addition :”+ ans1);

console.writeLine(“\n Subtraction :”+ ans2);

Console.writeLine(“\n Multiplication :”+ ans3);

}

}

 

OUTPUT:

Adiition: 300

Subtraction: 100

Multiplication: 200

Multicast Delegates

The second thing to note about the example is that all delegates can be constructed in this fashion, to create a delegate instance which refers to. a single method. However, as we noted before, some delegates-termed ‘multicast delegates‘ – can simultaneously reference multiple methods. These delegates must-like our Print delegate – specify a ‘void’ return type•

One manipulates the references of multicast delegates by using addition and subtraction.

The following code gives some examples:

print s = null;

s = s + new print (realMethod);

s += new print (otherRealMethod);

The – and – = operators are used in the same way to remove method references from a delegate.

The following code gives an example of the use of multicast delegates.

Use of Multicast delegates

 

using system;

delegate void Multiel();

class MD

{

static public void Hello()

{

console.writeLine(“Hello”);

}

static public void show()

{

console.writeLine(” Hi”);

}

}

class Test

{

public static void Main()

{

//delegate instances

Multioel Ml = new Multioel(Mo.Hello);

Multioel M2 = new Multioel(Mo.hello);

}

/combine the delegates

Multioel M3 = Ml + M2;

Multioel M4 = M2 + Ml;

//extracting the delegates

Multioel M5 = M3 – M2;

Multioel M6 = M4 – Ml;

//invoking delegates

M3 () ;

M4();

M5();

M6();

}

}

 

OUTPUT:

Hello

Hi

Hi

Hello

hello

Hi

Delegates vs. Interface

Delegates and interfaces are similar in that they enable the aspiration of specification and implementation. Multiple independent authors can produce implementations that are compatible with an interface specification. Similarly, a delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification. When should you use interfaces, and when should you use delegates?

Delegates are useful when

• A single method is being called.

• A class may want to have multiple implementations of the method specification.

• It is desirable to allow using a static method to implement the specification.

• An event like design pattern is desired.

• The caller has no need to know or obtain the object that the method is defined on.

• The provider of the implementation wants to “hand out” the implementation of the specification to only a few selected components.

• Easy composition is desired

Interfaces are useful when:

• The specification defines a set of related methods that will be called.

, • A class typically implements the specification only one.

• The caller of the interface wants to cast to or from the interface to obtain interface or classes.

Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C# Tutorials

C# Tutorials

  • C# - .NET Languages Types
  • C# - Dot Net
  • C# - Dot Net Framework
  • C# - Inheritance Types
  • C# - Features
  • C# - CTS
  • C# - CLS
  • C# - CLR
  • C# - Console
  • C# - MSIL
  • C# - Base Class Library
  • C# - Web Forms Creation
  • C# - C# Vs C++
  • C# - Statements Types
  • C# - JIT
  • C# - CLI
  • C# - Controls Types
  • C# - String Types
  • C# - Execution Model

Other Links

  • C# - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW