CSharp - Delegate Delegates Definition

Introduction

A delegate is an object that knows how to call a method.

You can think delegate as a function pointer or a type for method.

A delegate type defines the method's return type and its parameter types.

The following defines a delegate type called ConverterFunction:

delegate int ConverterFunction (int x);

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

ConverterFunction can reference any methods with an int return type and a single int parameter.

Here ConverterFunction is the method type name, we can define method variable whose type is ConverterFunction.

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

or this:

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

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

ConverterFunction t = Square;

Then we can invoke Square using t and passin the parameter.

It is like that we create a new method called t.

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

Here's a complete example:

Demo

using System;
delegate int ConverterFunction (int x);

class Test//from  w w  w .j  a v a  2  s  . c  o m
{
       static void Main()
       {
         ConverterFunction t = Square;    // Create delegate instance
         int result = t(3);               // Invoke delegate
         Console.WriteLine (result);      // 9
       }
       static int Square (int x) => x * x;
}

Result

Related Topics

Quiz