C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » ASP.NET/Web Applications »

Delegates in C# & VB.NET


Posted Date: 27 Oct 2009    Resource Type: Articles    Category: ASP.NET/Web Applications
Author: LaljiMember Level: Diamond    
Rating: 1 out of 5Points: 12



A delegate is an object that holds a reference to a method with a particular parameter list and return type.

It is basically like an object-oriented, type-safe function pointer.

Delegates basically make it possible to treat methods as entities. You can then assign a delegate to a variable or pass it as a parameter.

The classic delegate example uses events.

In C#:

HelloButton.Click += new EventHandler(HelloButton_Click);

Or the short-cut version of this code:

HelloButton.Click += HelloButton_Click;

This passes the HelloButton_Click method to a new EventHandler delegate.

In VB:

AddHandler HelloButton.Click, AddressOf HelloButton_Click

In VB, the AddressOf assigns the address of the HelloButton_Click method to the delegate.

Instead of using a named method for the delegate (in this example, a HelloButton_Click method), you can use a lambda expression.

In C#:

HelloButton.Click += (s, ev) =>
MessageBox.Show("Hello World");

In VB:

AddHandler HelloButton.Click, Function(s, ev) _
MessageBox.Show("Hello World")

In this case the lambda expression has two parameters: s (sender) and ev (eventArgs). When the Click event is generated on the HelloButton, the code displays the MessageBox.

You can use a lambda expression (inline function) anywhere a delegate is required. However, if the function requires more than a few lines of code, a named method is the preferred and recommended technique.



Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Delegates in C# & VB.NET  .  Delegates  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Data Type Conversions in C#.net
Previous Resource: Web site access permission.
Return to Discussion Resource Index
Post New Resource
Category: ASP.NET/Web Applications


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use