Hello
Im new to c# , I found delegates very difficult to understood can any one recommend a good sites , examples , books or any thing that can make it simple to me ,, thank you

Dani AI

Generated

Brief primer building on 's question and the pointers from and .

Think of a delegate as a type that describes a method signature and can hold references to any method that matches that signature. That makes delegates useful for callbacks, simple plug-ins, and wiring behaviour at runtime. They are objects (not plain pointers), can reference static or instance methods, and can form multicast lists (multiple methods invoked in sequence).

A minimal example showing declaration, assignment, lambda and multicast:

public delegate int Transformer(int x);

static int Square(int x) => x * x;

static void Main()
{
    Transformer t1 = Square;           // method group
    Transformer t2 = x => x * 2;       // lambda
    Transformer both = t1 + t2;        // multicast
    Console.WriteLine(t1(3));          // 9
    foreach (Transformer d in both.GetInvocationList())
        Console.WriteLine(((Transformer)d)(3));
}

Practical notes and modern habits:

  • Prefer built-in delegates (Action, Func, Predicate) unless a named delegate adds clarity.
  • When exposing external callbacks use events to prevent outsiders from invoking the delegate directly, for example:
    public event EventHandler SomethingHappened;
    void OnSomething() => SomethingHappened?.Invoke(this, EventArgs.Empty);
  • Beware multicast return values: when multiple methods are attached, the overall call returns only the last method's return value. If all results matter, iterate GetInvocationList() and collect them.
  • Delegates are immutable; += and -= produce new instances. Use the null-conditional invoke (?.Invoke) or a local copy to avoid race conditions on older runtimes.

Summary: start by declaring a tiny delegate, try assigning a method and a lambda, and experiment with multicast and GetInvocationList() to see behavior. This approach clarifies how delegates model "callable behavior" and when events or built-in delegates are preferable.

Recommended Answers

All 2 Replies

Hello
Im new to c# , I found delegates very difficult to understood can any one recommend a good sites , examples , books or any thing that can make it simple to me ,, thank you

Hi,

Delegates are the objects that stores reference to methods. This is similar to "Function Pointers" in vc++, but delegates are type safe.
It is not much difficult to understand. U can find more information in MSDN site.

http://msdn2.microsoft.com/en-us/library/ms173171.aspx

Thanks,
Kedar

Delegates are nothing but function pointers. You can read the book C# and .Net Platform by Andrew Troelson. I am giving an example here with necessary comments. It converts a number from decimal to binary and vice versa.

using System;


namespace Conversion
{


public class Conversion
{
/// <summary>
/// Summary description for Class1.
/// </summary>
//Function to convert decimal to binary
public static string dectobin(int n)
{
string s="";
int r;
while (n>1)
{
r=n%2;
s=s+Convert.ToString(r);
n=n/2;
}
s=s+Convert.ToString(n);
return s;
}


//Function to convert binary to decimal
public static int bintodec(int b)
{
double p=0;
int dec=0;
int x=2;
int y;
while (b!=0)
{
y=b%2;
dec=dec+(int)(y*Math.Pow(x,p));
b=(b-y)/10;
p++;
}
Console.WriteLine("{0}",dec);
return dec;
}


//Declaration of delegates for both functions
public delegate string deldectobin(int k);
public delegate int delbintodec(int m);


/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]


public static void Main(string[] args)
{
//Creating a delegate object
deldectobin del;
del=new deldectobin(dectobin);
delbintodec delb;
delb=new delbintodec(bintodec);
int t=0;
int a=0,op;
string w="";
int q,g;
int f;
do
{
Console.WriteLine("**********Conversion***********");
Console.WriteLine("1. Decimal to Binary");
Console.WriteLine("2. Binary to Decimal");
Console.WriteLine("3. Quit");
Console.WriteLine("Please enter your choice :");
op=Convert.ToInt32(Console.ReadLine());
switch(op)
{
case 1:
Console.WriteLine("Enter a decimal number   :");
t=Convert.ToInt32(Console.ReadLine());
//Calling the function with the delegate
w=del(t);
Console.Write("The Binary equivalent of {0} is :",t);
for (int k=w.Length-1;k>=0;k--)
Console.Write(w[k]);
Console.WriteLine();
break;
case 2:
Console.WriteLine("Enter a binary number    :");
readval:
f=Convert.ToInt32(Console.ReadLine());
q=f;
while (q!=0)
{
g=q%10;
if (g>1)
{
Console.WriteLine("Illegal value! Please retype");
goto readval;
}
q=(q-g)/10;
}



a=delb(f);


Console.WriteLine("Decimal Equivalent of {0} is : {1}",f,a);
break;
default:
break;
}
}while (op<3);
}
}
}

Beuls

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.