Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Delegate & Action in C#

Tags:

c#

If I searched I will definitely get examples of showing what is a Delegate and Action. I have read the basic books giving examples of delegate.

But what I want to know is their use in the real world. Please do not give Hello World example or the Animal class they are far too basic

For e.g. :

  1. What are the difference between them
  2. When to use a delegate or action
  3. When not to use a delegate or action
  4. When they can be an over kill
like image 632
HatSoft Avatar asked Jul 07 '12 16:07

HatSoft


People also ask

What is difference between delegate and event?

A delegate specifies a TYPE (such as a class , or an interface does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate.

What is delegate with example?

Delegates Overview Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.

What is delegate explain?

A delegate is an object-oriented, managed, secure and type-safe function pointer in the . NET framework. A delegate signature includes its name, return type and arguments passed to it. Rather than passing data, a delegate passes a method to another method.


1 Answers

Action is a Delegate. It is defined like this:

public delegate void Action(); 

You could create your own delegate types similarly to how you would create abstract methods; you write the signature but no implementation. You then create instances of these delegates by taking the reference of a method.

class Program {     public static void FooMethod()     {         Console.WriteLine("Called foo");     }      static void Main()     {         Action foo = FooMethod; // foo now references FooMethod()         foo(); // outputs "Called foo"     } } 
like image 100
gotopie Avatar answered Oct 01 '22 03:10

gotopie