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
- Single Cast Delegate
This type is one that fires off a single method which has the same signatures.
- 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:
- For addition part:
- For multiplication part:
- For subtraction part:
I hope this article is useful for you… I look forward to getting your comments and feedback.
Thanks,
Vijay Prativadi.