Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are generic delegates in C#?
Using generic delegates, you do not need to define the delegate statement. They are defined in the System namespace.
You can define a generic delegate with type parameters. For example −
delegate T myDelegete<T>(T n);
Example
The following is an example showing how to create generic delegates in C# −
using System;
using System.Collections.Generic;
delegate T myDelegete<T>(T n);
namespace GenericDelegateAppl {
class TestDelegate {
static int num = 5;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(50);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(10);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}Advertisements