Get to know Delegates - CSharp Custom Type

CSharp examples for Custom Type:delegate

Introduction

A delegate is a method type.

The following defines a delegate type called Transformer:

delegate int Transformer (int x);

Transformer is compatible with any method with an int return type and a single int parameter, such as this:

static int Square (int x) { return x * x; }

or more tersely:

static int Square (int x) => x * x;

Assigning a method to a delegate variable creates a delegate instance:

Transformer t = Square;

which can be invoked in the same way as a method:

int answer = t(3);    // answer is 9

Here's a complete example:

Demo Code

using System;//  w  w  w  .ja  v a2s.  c  o m
delegate int Transformer (int x);
class Test
{
   static void Main()
   {
      Transformer t = Square;          // Create delegate instance
      int result = t(3);               // Invoke delegate
      Console.WriteLine (result);      // 9
   }
   static int Square (int x) => x * x;
}

Result

The statement:

Transformer t = Square;

is shorthand for:

Transformer t = new Transformer (Square);

The expression:

t(3)

is shorthand for:

t.Invoke(3)

Related Tutorials