top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

What is a Delegate?

+9 votes
46 views

Please can anyone tell me the basic steps to create and use a delegate.

posted Feb 6, 2014 by Muskan

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

+3 votes
 
Best answer

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:

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.

answer Feb 6, 2014 by Amit Kumar Pandey
Similar Questions
+4 votes
+3 votes

How do we retrieve the customized properties of a .NET application from XML .config file? Can we automate this process?

+2 votes

Pros n cons of using querystring over other methods!

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...