Click here to Skip to main content
15,905,686 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi,
what is the use of delegate in C#,explain with realtime practical example.
Posted
Updated 15-Jun-12 4:20am
v2
Comments
ZurdoDev 15-Jun-12 9:11am    
Have you googled this? This sounds like a homework question.
bbirajdar 15-Jun-12 10:20am    
Edit: Added the tag Homework

A Delegate is a reference to a function, in the same way that a TextBox variable is a reference to teh instance of a TextBox that appears on the screen.

They are surprisingly handy: you can use them to write code that can work to a variety of destinations without changing the code. For example, you could write a Print method that took a delegate:
C#
private void DoPrint()
    {
    string text = "hello world!";
    Print(text, PrintConsole);
    Print(text, PrintTextbox);
    }
private void PrintConsole(string s)
    {
    Console.WriteLine("Console: " + s);
    }
private void PrintTextbox(string s)
    {
    myTextBox.Text = "TextBox: " + s;
    }
private delegate void printDestination(string s);
private void Print(string s, printDestination pd)
    {
    pd("From Print: " + s);
    }
You can completely change what happens to the text without changing the code in the Print method.

There are a lot of other uses, but that's the general idea.
 
Share this answer
 
I am not sure if you may have seen the following. These two are equivalent:

C#
datePicker.Loaded += (s, a) =>
{
    var textBox1 = (TextBox)datePicker.Template.FindName("PART_TextBox", datePicker);
    textBox1.Background = datePicker1.Background;
};

datePicker.Loaded += delegate
{
    var textBox1 = (TextBox)datePicker.Template.FindName("PART_TextBox", datePicker);
    textBox1.Background = datePicker1.Background;
};


Both these use the RoutedEventHandler delegate:

public delegate void RoutedEventHandler(object sender, RoutedEventArgs e);


You could also do the following

C#
void datePicker_Loaded(object sender, RoutedEventArgs e)
{
    var textBox1 = (TextBox)datePicker.Template.FindName("PART_TextBox", datePicker);
    textBox1.Background = datePicker1.Background;
}


then you would assign the handler as:

DatePicker.Loaded += new RoutedEventHandler(datePicker1_Loaded);


or

DatePicker.Loaded += datePicker1_Loaded;
 
Share this answer
 
Generally Delegates are Similar to C++ Function Pointers.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900