C# Simple Delegate Example
A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. 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.
Below C# Program Displays Results using Delegates. Here Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.
using System;
namespace Zappmania.Example.Delegate
delegate int MyDelegate(int a, int b);
public class TestClass
public static void Main(string[] args)
var myClassObj = new MyClass();
var sum = new MyDelegate(myClassObj.Add);
var multiply = new MyDelegate(myClassObj.Multiply);
var subtract = new MyDelegate(myClassObj.Subtract);
var sumResult = sum(23, 32);
Console.WriteLine("Result for Add is " + sumResult);
var multiplyresult = multiply(25, 2);
Console.WriteLine("Result for Multiply is " + multiplyresult);
var subtractResult = subtract(75, 42);
Console.WriteLine("Result for Subtract is " + subtractResult);
Console.ReadLine();
internal class MyClass
internal int Add(int a, int b)
return a + b;
internal int Multiply(int a, int b)
return a * b;
internal int Subtract(int a, int b)
return a - b;
Result for above code is :
Result for Add is 55
Result for Multiply is 50
Result for Subtract is 33
C# Simple Delegate Example
No comments:
Post a Comment