3

So say I've got a method which I've overloaded. One takes a function returning uints, one takes a function returning ints.

static void test1(Func<uint> f)
{
    //things
}
static void test1(Func<int> f)
{
    // also things
}

Now I try to call it like this:

test1(Random.FunctionThatReturnsUints);

but I get an ambiguous call error at compile time:

   Error    4   The call is ambiguous between the following methods or
    properties: 'RNG_Comparison.Run.test1(System.Func<int>)' and 'RNG_Comparison.Run.test1
(System.Func<uint>)'

What's up with that? Isn't the whole point of overloading a function for it to understand implicitly which one you mean based on the types? I mean, if I'd called it with a func returning BigInt or something, maybe I could see the compiler's confusion, but this one seems pretty cut and dried.

Does anyone know why I'm getting that error?

NathanTempelman
  • 1,301
  • 9
  • 34

2 Answers2

1

Eric Lippert (a member of the C# team) called this sort of thing "one of the hairiest parts of the spec", so to fully answer "why does the compiler do this?" would be a hard question. Suffice to say, it's because the C# specification allows that to happen. This is an easy workaround:

test1(new Func<uint>(Random.FunctionThatReturnsUints));
Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • 1
    Thanks for the shout-out; I note that I am a *former* member of the C# language design and compiler development teams. – Eric Lippert Sep 26 '13 at 19:28
1

The important thing in the post by Eric Lippert cited by Tim is:

The principle here is that determining method group convertibility requires selecting a method from a method group using overload resolution, and overload resolution does not consider return types.

In your code there's method group conversion in action and that causes the problem. The proposed solution eliminates the problem.

Community
  • 1
  • 1
ilmatte
  • 1,732
  • 16
  • 12