CSharp - Delegate and method overloading

Introduction

The compiler can bind the correct overloaded method.

Demo

using System;

public delegate int Mydel1(int x, int y);
public delegate int Mydel2(int x, int y, int z);

class A//w w w  .j  a va 2  s  .c  o m
{
    //Overloaded non static Methods
    public int Sum(int a, int b) { return a + b; }
    public int Sum(int a, int b, int c) { return a + b + c; }
}

class Program
{
    static void Main(string[] args)
    {
        int a = 25, b = 37, c = 100;
        A obA1 = new A();
        A obA2 = new A();

        Mydel1 del1 = obA1.Sum;
        Console.WriteLine("del1 is pointing Sum(int a,int b):");
        //Pointing Sum(int a, int b)
        Console.WriteLine("Sum of a and b is: {0}", del1(a, b));

        Mydel2 del2 = obA1.Sum;//pointing Sum(int a, int b, int c)
        Console.WriteLine("del2 is pointing Sum(int a,int b,int c):");
        //Pointing Sum(int a, int b, int c)
        Console.WriteLine("Sum of a, b and c is: {0}", del2(a, b, c));
        //same as
        //Console.WriteLine("Sum of a, b and c is: {0}", del2.Invoke (a, b, c));
    }
}

Result

Related Topic