Click here to Skip to main content
Click here to Skip to main content

Tagged as

Delegates in C#

, 27 Nov 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Main Interrelated Concepts of Delegates in C#

Introduction

Let’s play around with the main interrelated concepts of delegates in C#.

Today, in this article, we will dig out and play around by creating a simple delegate program and let’s see how better we can perform in this single program only. I mean, in this program, I will cover all stuff required for delegates from all the possible ways. So I will be covering simple delegate creation, multi-cast delegate, use of named methods, use of anonymous methods, use of lambda expression and finally a much better implementation about all of these and generic delegates as well.

What are Delegates?

Definition

Delegate is an object which cross references the method which you want to actually point and fire. The method signature must match with delegate variable parameters declaration. It’s Type Safe.

Question Arises: When To Use This Stuff????

You would use this when:

  • You want to pass on some anonymous methods.
  • You want to chain multiple methods using single operated action.
  • You don’t have to create an extra method. To get rid of overhead methods with usage simple lambda expressions.
  • You are very eager to ease combination and follow design patterns.
  • You are eager to differentiate declarations and implementations.

Types of Delegates

  1. Single Cast Delegate

    This type is one that fires off a single method which has the same signatures.

  2. Multi Cast Delegate

    This type is one that fires off multiple methods which has the same signatures.

What are Named Methods?

The delegates which are interrelated with some predefined methods in our application which are assigned to delegate variables are called as Named methods.

Example

VijayDelegates<int, int>  p = new VijayDelegates<int, int>(b.Add);
	int result = p(22, 20);
Response.Write("<center><b><i><h1>" + result + "</h1></i></b></center>");

What are Anonymous Methods?

We can simply say that these methods are those which do not have any specific name but indeed perform an expected operation by passing itself as a value parameter to delegate.

Example

VijayDelegates<int, int> p;
p = delegate(int r1, int r2)
{
    return r1 * r2;
};
int result = p(34, 3);
Response.Write("<center><b><i><h1>" + result + "</h1></i></b></center>");

What is Lambda Expression?

Lambda Expression holds a block of code with expression and statements which perform an expected operation without creating much overhead with lambda operator where it goes and fetches the data by overlooking towards anonymous methods.

Example

VijayDelegates<int, int> p;
p = (x, y) => x / y;
int result = p(500, 20);
Response.Write("<center><b><i><h1>" + result + "</h1></i></b></center>");

What is GenericDelegate?

It accepts data in the delegate variable to be user-defined which enables to easily typecast the intended data. It is denoted by Type <T>.

Example

public delegate int VijayDelegates<T1, T2>(T1 var1, T2 var2);

Now, we don’t like to waste much more time on studying the theory. It’s time for us to get started with delegates.

For all these concepts implementation and demonstration, I will now be creating a simple webform in 4.0 with C#. I have created four buttons and added a simple CSS to enhance the look and feel of the application. I have performed the delegate operations in code behind file.

The complete source code for WebForm1.aspx looks like this:

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="WebForm1.aspx.cs" Inherits="Simple_Delegates_Web_Application.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<style type="text/css">
.class
{
    font-style: oblique;
    color: #800000;
    font-family: Cambria;
    font-size: large;
    font-weight: bold
    }

</style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <center>
        <asp:Button ID="Button1" runat="server" Text="Addition" Width="107px"
            onclick="Button1_Click" CssClass="class" />
        <br />
        <br />
        <asp:Button ID="Button2" runat="server" Text="Substraction"
            onclick="Button2_Click" CssClass="class"/>
        <br />
        <br />
        <asp:Button ID="Button3" runat="server" Text="Multiply" Width="105px"
            onclick="Button3_Click" CssClass="class"/>
        <br />
        <br />
         <asp:Button ID="Button4" runat="server" Text="Division" Width="105px"
            onclick="Button4_Click" CssClass="class"/>
        <br />
        <br />
    </center>
    </div>
    </form>
</body>
</html>

The complete source code for Class1.cs looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace Simple_Delegates_Web_Application
{
    public class Class1
    {
        public int Add( int x, int y)
        {
            return x + y;
        }
        public int Sub(int x, int y)
        {
            return x - y;
        }
    }
}

The complete source code for WebForm1.aspx.cs looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Simple_Delegates_Web_Application
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        public delegate int VijayDelegates<T1, T2>(T1 var1, T2 var2);
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        Class1 b = new Class1();
        protected void Button1_Click(object sender, EventArgs e)
        {
          VijayDelegates<int, int>  p = new VijayDelegates<int, int>(b.Add);
          int result = p(22, 20);
          Response.Write("<center><b><i><h1>" + result + "</h1></i></b></center>");
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            VijayDelegates<int, int> p = new VijayDelegates<int, int>(b.Sub);
            int result = p(30, 20);
            Response.Write("<center><b><i><h1>" + result + "</h1></i></b></center>");
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            VijayDelegates<int, int> p;
            p = delegate(int r1, int r2)
            {
                return r1 * r2;
            };
            int result = p(34, 3);
            Response.Write("<center><b><i><h1>" + result + "</h1></i></b></center>");
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            VijayDelegates<int, int> p;
            p = (x, y) => x / y;
            int result = p(500, 20);
            Response.Write("<center><b><i><h1>" + result + "</h1></i></b></center>");
        }
    }
}

The output of this program looks like this:

  1. For addition part:

  2. For multiplication part:

  3. For subtraction part:

I hope this article is useful for you… I look forward to getting your comments and feedback.

Thanks,
Vijay Prativadi.

License

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

Share

About the Author

Vijay_Prativadi
Software Developer
India India
This is Vijay Prativadi. Specialized in Developing Web Apps using C#.NET, ASP.NET, MVC.
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 1 PinprofessionalNguyen.H.H.Dang6-Jul-14 23:56 
GeneralMy vote of 3 PinmemberShlomiO30-Nov-11 9:20 
Nice article, litle messy.
GeneralMy vote of 1 PinmemberVijay Gill28-Nov-11 23:50 
GeneralMy vote of 1 PinmemberJasmine250128-Nov-11 13:17 
GeneralMy vote of 2 PinmemberGeorgi Atanasov28-Nov-11 12:06 
GeneralMy vote of 3 Pinmembercjb11027-Nov-11 23:21 
GeneralMy vote of 3 Pinmembergreg_echo27-Nov-11 20:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141216.1 | Last Updated 27 Nov 2011
Article Copyright 2011 by Vijay_Prativadi
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid