hi all ,
i have a bit misunderstand with the delegate
the first one is why we have the verify if the delegate null or no ?
public class MyClass
{
// Declare a delegate that takes a single string parameter
// and has no return type.
public delegate void LogHandler(string message);
// The use of the delegate is just like calling a function directly,
// though we need to add a check to see if the delegate is null
// (that is, not pointing to a function) before calling the function.
public void Process(LogHandler logHandler)
{
if (logHandler != null)
{
logHandler("Process() begin");
}
if (logHandler != null)
{
logHandler ("Process() end");
}
}
}
the second one is why we have to refer the delegate with null and sometimes no?
like this:
MyClass.LogHandler myLogger = null;
myLogger += new MyClass.LogHandler(Logger);
vs this:
MyClass.LogHandler myLogger = new MyClass.LogHandler(Logger);
please help me i can't understand those collision between them.
Loading
VulpesPosted Oct 5, 2012, 12:17 PM
Sukesh MarlaPosted Oct 5, 2012, 12:12 PM
Example
MyClass.LogHandler myLogger = null;
myLogger = new MyClass.LogHandler(Logger); //Delegate point to Logger Method
myLogger += new MyClass.LogHandler(Logger2);//Now delegate point to Logger and Logger2
myLogger += new MyClass.LogHandler(Logger3);//Now delegate point to Logger and Logger2 and Logger3
when u invoke myLogger Logger,Logger2 and Logger3 All will exeucted one after other.
Just like variable,
int i=1;
i+=4;// i is 5
i+=3;// i is 8
now if you say i=3 // i is 3
Similar way after adding Logger2 and Logger3
if you say myLogger=null; // now myLogger is not pointing to anything
now += acts as first +
in Short
MyClass.LogHandler myLogger = null;
myLogger += new MyClass.LogHandler(Logger);
and
MyClass.LogHandler myLogger = new MyClass.LogHandler(Logger);
Both are same//Second one will be better if you want to create single cast delegate
Hopw you understood
Check this is correct answer if it helped.
Sukesh MarlaPosted Oct 8, 2012, 10:26 AM
hocine chenikiPosted Oct 7, 2012, 1:28 AM