Singlecast Delegate in C#
In this article I will explain Singlecast delegates in C#.
Introduction
In this article I will explain Singlecast delegates in C# . Delegates is similar to a function pointer in C or C++ which can hold the reference of a function . It's a new type of object in C#. Delegate is very special type of object as earlier the entire the object we used to defined contained data but delegate just contains the details of a method.
Declaration
[attributes] [modifiers] delegate ReturnType Name ([formal-parameters]);
Modifiers
Modifier can be one of the following keyword
- public
- private
- protected
- internal.
ReturnType
The ReturnType can be any of the data types we have used.
Name
Name is delegate name.
Example
public delegate int Addsub(int a)
public is access modifier.
int is access ReturnType.
Addsub is the delegate name.
Types of Delegates
- Singlecast delegates
- Multiplecast delegates
Singlecast delegates
Singlecast delegate refer to single method at a time. In this the delegate is assigned to a single method at a time. They are derived from System.Delegate class.
Example
using System;
public delegate int Addsub(int a);
namespace DelegateAppl
{
class DelegateExample
{
static int num = 5;
public static int AddNum(int b)
{
num += b;
return num;
}
public static int subNum(int c)
{
num -= c;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
Addsub D1 = new Addsub(AddNum);
Addsub D2 = new Addsub(subNum);
D1(25);
Console.WriteLine("Value of Num: {0}", getNum());
D2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
The output of following program
