2

Say, we have ClassA with method Foo containing an optional parameter. So, we can use it as shown in method DoFoo.

public class ClassA
{
    public ClassA() { }

    public void Foo(bool flag = true)
    {
    }

    public void DoFoo()
    {
        Foo(); // == Foo(true);
    }
}

Once I needed to pass it to another class ClassB. First I tried to pass it as Action, but the signature surely didn't match. Then I passed it as Action<string>, the signature matched, but the parameter in ClassB was no longer optional. But I did wanted to have it optional and came to an idea to declare a delegate. So, it worked.

public delegate void FooMethod(bool flag = true);

public class ClassB
{
    Action<bool> Foo1;
    FooMethod Foo2;

    public ClassB(Action<bool> _Foo1, FooMethod _Foo2)
    {
        Foo1 = _Foo1;
        Foo2 = _Foo2;
    }

    public void DoFoo()
    {
        Foo1(true);
        Foo2(); // == Foo2(true);
    }

So, the question is: can I somehow pass a method with an optional parameter as an argument without explicitly declaring a delegate and keep the optional quality of its parameters?

horgh
  • 17,918
  • 22
  • 68
  • 123

1 Answers1

4

So, the question is: can I somehow pass a method with an optional parameter as an argument without explicitly declaring a delegate and keep the optional quality of its parameters?

No. The "optionality" is part of the signature of the method, which the compiler needs to know at at compile time to provide the default value. If you're using a delegate type that doesn't have the optional parameter, what is the compiler meant to do when you try to call it without enough arguments?

The simplest approach is probably to wrap it:

CallMethod(() => Foo()); // Compiler will use default within the lambda.
...
public void Foo(bool x = true) { ... }

public void CallMethod(Action action) { ... }
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Though this approach makes it impossible to pass not default parameters to `Foo`, I extremly like it, espesialy due to in my case, it's enough – horgh Oct 04 '12 at 14:05
  • As for my question, I thought I could be not aware of some C# way to define smth like `Action`... – horgh Oct 04 '12 at 14:09
  • @KonstantinVasilcov: "Something like" isn't detailed enough to know what you mean. You can declare your own delegate types of course, but if you want to declare a *generic* delegate type with an optional parameter of a generic type, the only default value would be default(T). – Jon Skeet Oct 04 '12 at 14:12