Define a delegate with no return value and no parameters

A delegate is an object that can refer to a method.
The method referenced by delegate can be called through the delegate.
A delegate in C# is similar to a function pointer in C/C++.
The same delegate can call different methods.
A delegate is declared using the keyword delegate.

The general form of a delegate declaration:

delegate ret-type name(parameter-list);

ret-type is return type.
The parameters required by the methods are specified in the parameter-list.

A delegate can call only methods whose return type and parameter list match those specified by the delegate's declaration.

All delegates are classes that are implicitly derived from System.Delegate.


Example
using System;
delegate void FunctionToCall();


class MyClass
{
public void nonStaticMethod()
{
Console.WriteLine("nonStaticMethod");
}

public static void staticMethod()
{
Console.WriteLine("staticMethod");
}
}

class MainClass
{
static void Main()
{
MyClass t = new MyClass();
FunctionToCall functionDelegate;
functionDelegate = t.nonStaticMethod;

functionDelegate += MyClass.staticMethod;
functionDelegate += t.nonStaticMethod;
functionDelegate += MyClass.staticMethod;

functionDelegate();
}
}


Shekhar Kadam
Software Engineer


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: