dotnetspider.com
Login Login    Register      

TutorialsForumCareer DevelopmentResourcesReviewsJobsInterviewCommunitiesProjectsTraining

Subscribe to Subscribers
Talk to Webmaster
Tony John

Facebook
Google+
Twitter
LinkedIn
Online MembersA'zlina
More...
Join our online Google+ community for Bloggers, Content Writers and Webmasters




Resources » .NET programming » General

Delegates : A Step Ahead Series


Posted Date:     Category: General    
Author: Member Level: Gold    Points: 15



 


Delegates : A Step Ahead Series
Introduction:
The scope of this article is limited to its title and upto subsequent examples shown therein. This tutorial is a part of C#:2005-A Step Ahead Series.
Definition :
A delegate is a type that references a method once delegate is assigned a method; it behaves exactly like that method. The delegate method can be used like any other method, with parameters and return value.
Any method that matches the delegate’s signature, which consists of the return type and parameters can be assigned to the delegate.
Delegate Properties:
Delegates have the following properties:

  • Delegates have are similar to c++ function pointer but are type safe.

  • Delegates allow method to be passed as parameters.

  • Delegates can be used to define callback methods.

  • Delegate can be chained together for example: multiple method can be called on a Single event.

  • In .Net2.0 introduced named method or anonymous method delegate.


Example:


public delegate void PrintDelegate(String name);


Named method:

Delegates in which the called methods are apart from delegate. In this we put a reference of the method in delegate, but the definition and signature of that methods are at other side. When instantiate a delegate then method is passed as a parameter.

The following Console snippet describe the working of Named Method:

using System;

namespace AstepAhead.namedmethod
{
public class delegateClass
{
public delegate void delegateAdd(int x, int y);

public static void AddNum(int x, int y)
{
Console.WriteLine(“Sum of {0},{1} = {2}”, x,y,x+y);
}

public static void Main()
{
Delaget Add myAddDel = newdelegateAdd(delegateclass.AddNum);

Console.WriteLine(“Enter first number : “);
Int num1= int.parse(Console.ReadLine());

Console.WriteLine(“Enter second number : “);
Int num2= int.parse(Console.ReadLine());

//Invoke named method

myAddDel*num1, num2);
Console.ReadLine();
}
}
}


Anonymous method:
In this we put entire code-block of a method within delegate as a parameter. It eliminates the need to create a separate method.

The Scope of the parameters of an anonymous method is the anonymous method-block. In an anonymous the use of jump statements like goto, break or continue are not allowed whose target is outside the anonymous method block. It cannot access the ‘ref’ ot ‘out’ parameters of an outer scope. Moreover, no unsafe code can be accessed within the anonymous method block.


using System;

namespace AstepAhead.anonymousmethod
{
public class delegateClass
{
public delegate void delegateAdd(int x, int y);


public static void Main()
{
delegatelass mydelcls = new delegateAdd();
mydelcls.delAdd mydellAdd = new mydelcls.delAdd(int a, int b)
{

Cosole.WrieLine(“Sum of {0}, {1} = {2}”, a,b, b+a);
}; //anonymous block

Console.WriteLine(“Enter first number : “);
Int num1= int.parse(Console.ReadLine());

Console.WriteLine(“Enter second number : “);
Int num2= int.parse(Console.ReadLine());

//Invoke named method

myAddDel*num1, num2);
Console.ReadLine();
}
}
}


Multicast Delegates :
A multicast delegate has a linked list of delegates, called an invocation list, consisting one or more elements. When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order which they appear of. An error occurs during execution of the list then on exception is thrown.


using System;

namespace AStepAhead.MulticastDelegate
{
public delegate void DelString(string str);

public class MulticastDelegate
{
public static void firstMethod(string x)
{
Console.WriteLine("It prints using first method.\nYou have entered:{0}", x);
}
public static void secondMethod(string y)
{
Console.WriteLine("\nIt prints using second method.\nYou have entered:{0}", y);
}
public static void thirdMethod(string z)
{
Console.WriteLine("\nIt prints using third method.\nYou have entered:{0}", z);
}
static void Main(string[] args)
{
Console.Clear();
Console.Write("Enter string : ");
string str = Console.ReadLine();
DelString myMultiDel1, myMultiDel2, myMultiDel3, myMultiDel4, myMultiDel5;

//Firs call method individually
myMultiDel1 = new DelString(firstMethod);
myMultiDel1(str);
Console.ReadLine();
myMultiDel2 = new DelString(secondMethod);
myMultiDel2(str);
Console.ReadLine();
myMultiDel3 = new DelString(thirdMethod);
myMultiDel3(str);

//Combine two delegates or multicast
Console.WriteLine("\nThis all using Multicast delegates\n");
myMultiDel4 = myMultiDel1 + myMultiDel2 + myMultiDel3;
myMultiDel4(str);

//another way to multicast
Console.WriteLine("\nThis all using Multicast delegates showing another way of multicasting\n");
myMultiDel5 = new DelString(firstMethod);

//multicasting or combining / attaching
myMultiDel5 += new DelString(thirdMethod);
myMultiDel5(str);

//deattaching
myMultiDel5 -= new DelString(firstMethod);
myMultiDel5(str);

Console.ReadLine();


}
}
}



Steps to test above:

  1. Open Console Window of available Visual Studio.

  2. Start - > Programs -> Visual Studio [version] ->Visual Studio Tools - >Console

  3. Now compile the abovefrom console as follow:

    />csc .exe delegateclass.cs



Above will produce an executable file, double click on this file.
Conclusion :
In sum up, we can say that a delegate is a type that references a method with following types:

  1. Named Method

  2. Anonymous Method

  3. MultiCast Delegate






Did you like this resource? Share it with your friends and show your love!


Responses to "Delegates : A Step Ahead Series"

No responses found. Be the first to respond...

Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: When we use Custom Control?When we use User Control? What is difference between these two?
    Previous Resource: Formatting Tags in HTML
    Return to Resources
    Post New Resource
    Category: General


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    Delegate - A Step Ahead Series  .  Multi Delegates  .  Named Method  .  Anonymous method  .  



    Follow us on Twitter: https://twitter.com/dotnetspider

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds


    About Us    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.