Let's Play Around With Main Interrelated Concepts of Delegates in C#

Today, in this article we will dig out and play around by creating 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 everything all stuff required for delegate 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 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 This Stuff????

  • You would use when you want to pass on some anonymous methods.
  • You would use when you want to chain multiple methods using single operated action.
  • You would use when you don't have to create an extra methods. To get rid of over headed methods with usage simple lambda expressions.\
  • You would use when you are very eager to easy combination and follow design patterns.
  • You would use when you eager to differentiate declarations and implementations.

Types of Delegates:

  1. Single Cast Delegate:

    This type is one that fires off single method which has same signatures.
     
  2. Multi Cast Delegate:

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

What are Named Methods?

The Delegates which are interrelated with some predefined methods in our application. Which are assigned to delegate variable are called as Named Methods.

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 simple say that these methods are that which does not have any specific name but indeed performs an expected operation by passing itself as a value parameter to delegate.

 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 block of Code with expression and statements which performs an expected operation without creating much over head with lambda operator where it goes and fetches the data by overlooking towards anonymous methods.

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 type cast the intended data. It is denoted by Type <T>.

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 this concepts implementation and demonstration I will be now creating simple webform in 4.0 with C#.  I have created four buttons and added simple CSS to enhance the Look and Feel of 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 id="Head1" 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>");

        }
    }
}


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....
 


Similar Articles
MVC Corporation
MVC Corporation is consulting and IT services based company.