A delegate is, in short , a pointer to a function.
That is, imagine that you can create a function and assign it to a variable to pass it as a parameter where you need it. Of course, inheriting all the characteristics of the CLR, including security and strong typing.
A delegate is a reference type that can be used to encapsulate a named or anonymous method. Delegates are similar to function pointers in C++, but are safer and provide better type safety.
A delegate is a type that represents method references with a given parameter list and return type. When a delegate is instantiated, you can attach its instance to any method using a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Example (msdn)
using System;
public class SamplesDelegate {
public delegate String myMethodDelegate( int myInt );
public class mySampleClass {
public String myStringMethod ( int myInt ) {
if ( myInt > 0 )
return( "positive" );
if ( myInt < 0 )
return( "negative" );
return ( "zero" );
}
public static String mySignMethod ( int myInt ) {
if ( myInt > 0 )
return( "+" );
if ( myInt < 0 )
return( "-" );
return ( "" );
}
}
public static void Main() {
mySampleClass mySC = new mySampleClass();
myMethodDelegate myD1 = new myMethodDelegate( mySC.myStringMethod );
myMethodDelegate myD2 = new myMethodDelegate( mySampleClass.mySignMethod );
Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 5, myD1( 5 ), myD2( 5 ) );
Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", -3, myD1( -3 ), myD2( -3 ) );
Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 0, myD1( 0 ), myD2( 0 ) );
}
}
/*
This code produces the following output:
5 is positive; use the sign "+".
-3 is negative; use the sign "-".
0 is zero; use the sign "".
*/
A delegate is an object that contains a reference to a method.
To create a delegate it is necessary to indicate what the parameters and the return type are , for example:
delegate double Operacion(double x);
Operacionis compatible with any method that returns a doubleand has only one parameter of type double, like this:
static double Cuadrado(double x) { return x * x; }
Assigning a method to a type variable Operacioncreates an instance of the delegate:
Operacion op = Cuadrado;
finally we can use that instance to call the method it references:
double resultado = op(4); // 16
In C#, delegates are commonly used in events and as callbacks to communicate between different parts of an application dynamically. Callbacks and delegates are so common that in C# 3 a new, more compact syntax was added in the form of lambda expressions to represent a delegate:
// Delegado anterior en forma de expresión lambda
Operacion op = x => x * x;
Although delegate behavior can be emulated with an interface, they have an additional feature called multicasting which means that a single instance can reference more than one method, for example:
MiDelegado d = Metodo1;
d += Metodo2; // Añade un nuevo método a la lista del delegado
Now when invoking dboth methods they will be called, the order in which they are called is the same as the order in which they are added to the delegate list.
A clear example of the use of delegates and callbacks is LINQ , the type List<T>has many methods that accept a delegate (or lambda expression) and perform different actions:
List<int> numeros = Enumerable.Range(1, 200).ToList();
var impares = numeros.Find(n => n % 2 == 1);
In this case the method Findaccepts a delegate type with one argument intand return type bool, through this callback we find the odd numbers in the list.
A delegate is C# 's way of declaring types whose function is function pointer. A delegate allows you to assign a signature to a name, so that all variables created based on that name are capable of storing pointers to functions compatible with that signature.
A delegate-based variable can point to either a member function of a class or a lambda.
What's the point of using delegates? The alternative would be to write the signature on each use instead of the delegate. Look for example at lower level languages like c or c++ . In these cases there is no concept of delegate as such. However, since writing the function signature in multiple places creates complicated code to manage, we choose to alias the function using typedefor the most recent using(in c++11 ). These aliases would be the equivalent of the C# delegate .
More than an analogy, I don't know if what they are for me in simple words works for you: a delegate allows you to send a method as a parameter to another method.
A delegate is a type that defines a method signature and can be associated with any method with a compatible signature. You can invoke (or call) the method through the delegate. Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are called through delegates.
example:
//Declaramos
public delegate void stackOverFlowEsDelegado(string mensaje, int cantidadVeces);
//Instanciamos
stackOverFlowEsDelegado delegadoDeEjemplo = new stackOverFlowEsDelegado(stackOverFlowEs);
//invocamos
delegadoDeEjemplo("ejemplo de delegado en stackoverflow ES", 5);
The function of delegates is to allow you to manipulate or work with objects within other threads within your application, otherwise when trying to access it, it would return an error or at least that is what I usually use delegates for.
A delegate in C# is like a data type that points to a method, thus allowing us to extend the capabilities of our code or allow others to do so. The way to declare a delegate is as follows: delegate().
A delegate is, in short , a pointer to a function.
That is, imagine that you can create a function and assign it to a variable to pass it as a parameter where you need it. Of course, inheriting all the characteristics of the CLR, including security and strong typing.
msdn:
msdn: Delegates (C# Programming Guide)
Example (msdn)
A delegate is an object that contains a reference to a method.
To create a delegate it is necessary to indicate what the parameters and the return type are , for example:
Operacion
is compatible with any method that returns adouble
and has only one parameter of typedouble
, like this:Assigning a method to a type variable
Operacion
creates an instance of the delegate:finally we can use that instance to call the method it references:
In C#, delegates are commonly used in events and as callbacks to communicate between different parts of an application dynamically. Callbacks and delegates are so common that in C# 3 a new, more compact syntax was added in the form of lambda expressions to represent a delegate:
Although delegate behavior can be emulated with an interface, they have an additional feature called multicasting which means that a single instance can reference more than one method, for example:
Now when invoking
d
both methods they will be called, the order in which they are called is the same as the order in which they are added to the delegate list.A clear example of the use of delegates and callbacks is LINQ , the type
List<T>
has many methods that accept a delegate (or lambda expression) and perform different actions:In this case the method
Find
accepts a delegate type with one argumentint
and return typebool
, through this callback we find the odd numbers in the list.A delegate is C# 's way of declaring types whose function is function pointer. A delegate allows you to assign a signature to a name, so that all variables created based on that name are capable of storing pointers to functions compatible with that signature.
A delegate-based variable can point to either a member function of a class or a
lambda
.What's the point of using delegates? The alternative would be to write the signature on each use instead of the delegate. Look for example at lower level languages like c or c++ . In these cases there is no concept of delegate as such. However, since writing the function signature in multiple places creates complicated code to manage, we choose to alias the function using
typedef
or the most recentusing
(in c++11 ). These aliases would be the equivalent of the C# delegate .More than an analogy, I don't know if what they are for me in simple words works for you: a delegate allows you to send a method as a parameter to another method.
according to msdn :
example:
In this article, you have a good example of delegate delegates C# example
Using delegates
The function of delegates is to allow you to manipulate or work with objects within other threads within your application, otherwise when trying to access it, it would return an error or at least that is what I usually use delegates for.
I hope I have helped you, regards.
A delegate in C# is like a data type that points to a method, thus allowing us to extend the capabilities of our code or allow others to do so. The way to declare a delegate is as follows: delegate().