delegate parameters

Polymorphic parameters for delegate

delegate can accept more specific parameters.


using System;//w  w  w.  j a v  a  2  s  .  c o  m
delegate void Printer(object t);

class Test
{
    static void consolePrinter(object str)
    {
        Console.WriteLine(str);
    }
    static void Main()
    {
        Printer p = consolePrinter;

        object obj = "java2s.com";
        p(obj);
    }
}

The output:

Delegate with reference paramemters

Delegate with reference paramemters


using System;/*from w  ww  .jav a 2  s  .  c  o  m*/

delegate void FunctionToCall(ref int X);

class MainClass
{
   public static void Add2(ref int x) { 
       x += 2; 
   }
   
   public static void Add3(ref int x) { 
       x += 3; 
   }

   static void Main(string[] args)
   {
      FunctionToCall functionDelegate = Add2;
      functionDelegate += Add3;
      functionDelegate += Add2;

      int x = 5;
      functionDelegate(ref x);

      Console.WriteLine("Value: {0}", x);
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor