Question : Can someone explain this code to me?

Hi gang,

I was reading a C# article about anonymous methods and delegates and I ran into this piece of code (see snippet for full source):

   delegate void DelegateType();
   static DelegateType GetMethod(){
      return new DelegateType(MethodBody);}

This has me scratching my head. First he defines a delegate called "DelegateType". Then he defines a method of type "DelegateType" which RETURNS a new object of type "DelegateType" which uses a regular method called "MethodBody" as a parameter. I get it that the net effect of or all of this is to create a pointer to the method called "MethodBody", but who why would you code it this way? Wouldn't you just code it like this:

DelegateType GetMethod = new DelegateType(MethodBody)

I would really appreciate it if someone could explain this to me in plain english.

Thanks in advance,
Kevin McElhiney
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
class Program {
   delegate void DelegateType();
   static DelegateType GetMethod(){
      return new DelegateType(MethodBody);
   }
   static void MethodBody() {
      System.Console.WriteLine("Hello");
   }
   static void Main() {
      DelegateType delegateInstance = GetMethod();
      delegateInstance();
      delegateInstance();
   }
}

Answer : Can someone explain this code to me?

Hi,
 >> static DelegateType GetMethod(){
      return new DelegateType(MethodBody);
   }

Why use the syntax above to create the delegate instance instead of this:

DelegateType test = new DelegateType(MethodBody);

yes, you can use.GetMethod creates new DelegateType  object and reurns the same.hope author of that article may want to show how to return delegate.as he creates and invokes delegate in static main method, he used static GetMethod method.you can make it in class and can invoke it as instatnt method.
Random Solutions  
 
programming4us programming4us