Quote:
> i'm studing c#, and i'm finding some difficulties to understand the part
relative to Events and Delegates.... maybe i'm using a bad book... or that
arguments are really hard.
there are a lot of good places to look at. just ask any search engine.
basically, delegates are just functions prototypes.
look at the simplest example:
public class Class3
{
public Class3() {}
public delegate void D(int a);
public static void FN( int p, D f )
{
if ( f!=null ) f(p);
}
}
delegate D defines a type that can be used to pass a pointer to a function
to the function FN. Look how I use the name of the delegate, D. I use it as
if it was a type name! inside FN I can use this delegate (read: pointer to
the function), named 'f', by just invoking it ( f(p), of course I could do
whatever I would like to ).
look at the example on how to call this FN function and pass a pointer to
arbitrary function to it:
public class Class4
{
public Class4() {}
// this one will be passed as a pointer
public static void testFN(int a)
{
Console.WriteLine ( a.ToString() );
}
// call this one to test the whole thing
public static void TEST_DELEGATE()
{
Class3.FN ( 1, new Class3.D ( Class4.testFN ) );
}
}
here, I define my own function, testFN that will match the delegate
definition from Class3.
in function TEST_DELEGATE() I call the Class3.FN() that expects:
a) an int -> I pass the value of 1
b) a pointer to a function that returns void and expects a single parameter
of type int. I initialize this parameter by this new syntax:
new Class3.D ( Class4.testFN )
which means: take the Class4.testFN and pass it to Class3.FN as a pointer
(to be able to call it inside Class3.FN)
if I call Class3.TEST_DELEGATE() it will pass both arguments to Class3.FN
and inside it it will combine the function pointer with the parameter and
call it.
if ( f!=null ) f(p);
in this example the function just writes the value to the console.