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

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

Edited 3 Years Ago by happygeek: fixed formatting

This article has been dead for over six months. Start a new discussion instead.