1

We know that we can reference to methods by using delegates and can call the methods by calling the instance of delegate.

I want to call a method(which has an optional parameter) by calling instance of delegate.

My code is below

using System;

namespace Testing_Delegates
{
    class Program
    {
        delegate void Order(string abc);
        public static void ReverseOrder(string rev = "Optional Param")
        {
            char[] elements = rev.ToCharArray();
            char[] reversed = new char[rev.Length];
            for(int i = 0; i < rev.Length; i++)
            {
                reversed[i] = elements[rev.Length - (i+1)];
            }
            foreach(char element in reversed)
            {
                Console.Write(element);
            }
        }


        static void Main(string[] args)
        {
            Order changeorder = new Order(ReverseOrder);
            changeorder();//------Here is error------------
        }
    }
}

Error is

There is no argument given that corresponds to the required formal parameter 'abc' of 'Program.Order'

Kyle McNally
  • 104
  • 2
  • 12
mdadil2019
  • 807
  • 3
  • 12
  • 29
  • Possible duplicate of [Can a Delegate have an optional parameter?](http://stackoverflow.com/questions/3763037/can-a-delegate-have-an-optional-parameter) – sr28 Aug 19 '16 at 11:28

5 Answers5

3

You can't do that. The delegate signature only knows about its own parameters (just like an Interface) and not about the delegate implementation. If you don't want to duplicate code, you can make the delegate signature accept the optional string and remove the optional string from the actual method implementation.

Jean Lourenço
  • 675
  • 6
  • 17
2

To get this to work you need to add the optional parameter to your delegate declaration as well. The declaration of the delegate should be:

delegate void Order(string abc = "Optional Param");

The default string can be any compile-constant string value.

Should also mention that doing this means that the ReverseOrder method doesn't need to have the optional parameter. It can be declared as:

public static void ReverseOrder(string rev) { ... }
1

The delegate's signature requires a parameter to be set. You will need to provide the value for string abc and also invoke like so:

changeorder.Invoke("hello world");
Oluwafemi
  • 14,243
  • 11
  • 43
  • 59
1

Add the default value to the delegate as well, like

delegate void Order(string abc = "Optional Parameter");
mjepson
  • 871
  • 1
  • 9
  • 21
1

You need your delegate signatures to also support optional parameter, currently your method signature and delegate signature are not same:

delegate void Order(string abc="");
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160