System ProgrammingLearn about Method delegates in C# Programming

Learn about Method delegates in C# Programming

Earlier in this series, you examined functions, how they can encapsulate a block of code, how they may accept parameters, do some processing and then they may or may not return an output. All this is great but have you ever thought about using functions the same way you use variables? Yes I mean passing them to other functions in the same way you pass normal variables, possibly returning them the same way you return a value from a function. Welcome to function delegates.

The first question that might pop into your head is: “Why should we use functions that way?” The typical usage of function delegates will be very obvious when you start working with events call-back methods. But let’s leave that aside for the moment and start learning about the concept first.

If you come from a C or C++ environment, you can regard delegates the same way you regard pointers to functions. Otherwise, consider a delegate as a reference type variable that references a function (called a method henceforth).

An example is the best way to understand what’s been just said. Take a look at the following code:

public delegate string ExampleDelegate(string s);

There is no difference between a method declaration and a delegate one except for two things:

  • The keyword delegate is added before the return type
  • There is no method body.

Note that this is just a declaration, you haven’t instantiated your delegate yet. To do so, first, you have to have a method that has the same signature as the delegate. A signature of a method is its parameter list and return type. That is, string ExampleMethod(string str) { } has the following signature: it has a return type of string and takes one string parameter. Accordingly, we have to create a method with the same signature as ExampleDelegate’s. Let’s do just that:

static string ExampleMethod(string str) 
{
    return str.ToUpper();
}
Now we are ready to start instantiating our delegate, and start using it:
static void Main(string[] args)
{
     ExampleDelegate cap = new ExampleDelegate(ExampleMethod);
     Console.WriteLine(cap("ahmad"));
     Console.ReadLine();
 }

Instantiating a delegate is done by using the new keyword followed by the delegate. The delegate here is used like a function, accepting the method name as an argument. Notice that we passed the method name without the parentheses, because we are not calling it, we’re just passing its reference. Once we have our delegate method, greeter, we can use it the same way we would use ExampleMethod. It would print whatever string we pass in uppercase.

The complete code is listed below:

class Program
    {
        public delegate string ExampleDelegate(string s);

        static string ExampleMethod(string str) 
        {
            return str.ToUpper();
        }

        static void Main(string[] args)
        {
            ExampleDelegate cap = new ExampleDelegate(ExampleMethod);
            Console.WriteLine(cap("Ahmad"));
            Console.ReadLine();
        }
    }

Learn Cloud Computing from Scratch for Beginners

Now to see the real power of delegates, consider the following situation: you are developing an application that would take text and format it so that it can appear on web pages as HTML. If you don’t know HTML, it’s a language that adds tags to text to make it appear with a specific look on web pages. For example <a href=”www.google.com”>www.google.com</a> will make www.google.com appear as clickable text (hyperlink) on a web page like this www.google.com. Ok, this is easy, you develop a method that would take www.google.com, add the necessary tags like this:

static string hyperlink(string str) 
{
    return "<a href='" + str + "'>" + str + "</a>";
}

But hyperlinks are not the only tags that may be on a typical web page, there are other tags like, for example, the <p></p> tag, which formats text in between it as a paragraph. Ok, nothing different here as far as a C# developer is concerned, let’s create a method for this as well:

static string paragraph(string str)
        {
            return "<p>" + str + "</p>";
        }

You call the appropriate method whenever the specific formatting is needed. But later on, you are required to add some heading text before the output of both methods: “The link is” followed by the URL whether it is in a hyperlink, or a paragraph. Modifying each method separately is a waste of time. Let’s use delegates instead:

class Program
    {
        public delegate string FormatterDelegate(string s);

        static string hyperlink(string str) 
        {
            return "<a href='" + str + "'>" + str + "</a>";
        }

        static string paragraph(string str)
        {
            return "<p>" + str + "</p>";
        }

        static string format(string s, FormatterDelegate formatter)
        {
            return "The link is: " + formatter(s);
        }

        static void Main(string[] args)
        {
            FormatterDelegate hl = new FormatterDelegate(hyperlink);
            FormatterDelegate p = new FormatterDelegate(paragraph);
            string link = format("www.google.com",hyperlink);
            string text = format("www.google.com", paragraph);
            Console.WriteLine(link);
            Console.WriteLine(text);
            Console.ReadLine();
        }
    }

Let’s go through this step by step:

  1. You created a delegate for a method that would accept a string, and return a string.
  2. Then you created two methods with the same signature as the delegate (that is, accepting a string argument and returning a string value), one to format the string as a hyperlink, and another to format it as a paragraph.
  3. Finally, you created a general function: format(). This time, it accepts not only a string parameter s, but also a reference to any method that accepts a string and returns one, (a delegate). You named it formatter.
  4. Inside this general function, you return “The link is: ” followed by whatever output returned from the formatter method, after passing your string to it as a parameter.
  5. In the Main() function, you create two delegates to your formatting methods hyperlink and paragraph. You call them hl and p. Those will be the second-place arguments to the generic format() method.
  6. To test the output, you print the output of format() when a hyperlink reference is passed, and when a paragraph one is passed.

The output of the above code should be:

The link is: <a href='www.google.com'>www.google.com</a>
The link is: <p>www.google.com</p>

The key to understanding the usefulness of delegates in this example is to realize that the format() function does not care about what the method reference passed to it does to the text it accepts. You can make as many methods that format text to HTML tags as you wish, the format() method will return their output preceded by whatever text you want to add. Now if you are asked to change “The link is: ” to some other phrase, you have to change it only in one place. As mentioned, delegates have more powerful uses than this, discussed when we start examining events.

Conclusion

Today, we examined one of the powerful – and a bit advanced – topics of C#: delegates. You have learned what delegates are, how useful they can be, and how to define them and use them.

In the next article, we will start talking about new important topic: Error Handling. A topic that you shouldn’t miss; so, see you there.

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -