hocine cheniki

hocine cheniki

  • NA
  • 5
  • 7.9k

Delegate and Null

Oct 5 2012 11:41 AM
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.

Answers (4)