Question:
I have been researching about delegates in C# but the truth is not that clear to me yet.
Can someone explain to me what it is about?
Answer:
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.
msdn: Delegates (C# Programming Guide)
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 "".
*/