Define a delegate with no return value and no parameters : delegate « delegate « C# / CSharp Tutorial






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

The general form of a delegate declaration:

delegate ret-type name(parameter-list);
  1. ret-type is return type.
  2. 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.

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();
   }
}
nonStaticMethod
staticMethod
nonStaticMethod
staticMethod








9.1.delegate
9.1.1.Define a delegate with no return value and no parameters
9.1.2.Add both static and non-static function to a delegate
9.1.3.Delegate with reference paramemters
9.1.4.Delegate with return values
9.1.5.Use a delegate to call object methods
9.1.6.delegate is a function pointer
9.1.7.A simple delegate example.
9.1.8.Construct a delegate using method group conversion
9.1.9.Delegates can refer to instance methods
9.1.10.Delegates to Instance Members
9.1.11.uses the invocation list to calculate a factorial
9.1.12.named-delegate invocation
9.1.13.Use delegate to reference two static functions
9.1.14.Declare a delegate and assigns a reference to either the WriteLine method or the ShowWindowsMessage method to its delegate instance.