2

Just ran into some unexpected behavior with how an overload was selected:

[TestFixture]
public class Foo {

    [Test]
    public void Do() {
        Do(() => {
            Console.WriteLine("Action Do");
        });
        try {
            Do(() => {
                Console.WriteLine("Func Do");
                throw new Exception();
            });
        } catch { }
    }

    public void Do(Action a) {
        a();
    }

    public void Do(Func<int> a) {
        a();
    }
}

This will output:

Action Do
Func Do

Basically, the second call to Do, while still not returning a value, selects the overload requiring a `Func.

My best guess is that because it always ends in an exception, the compiler can legally pick either signature. But what it the reasoning at this point for picking one over the other and allowing a lambda that clearly never returns anything to be matched with Func<T> rather than Action?

Arne Claassen
  • 14,088
  • 5
  • 67
  • 106
  • 1
    Note that while the duplicate discusses infinite loops inside lambda expressions, and this discusses guaranteed throws, both result in the same compiler behavior. The accepted answer even discusses this case. – p.s.w.g Jun 25 '14 at 21:18

0 Answers0