0

The following code gives the error:

no best type found for implicitly typed array

But why? All methods have the same signature, so I'd expect the type inference to succeed.

  • Notes:
    • I'm using .NET Framework 4.7.2.
    • I'm aware I can use an explicit array declaration, but I'm interested in understanding the reason for the error.

Code (live demo):

    public class Program
    {
        public static void Main()
        {
            var validators = new[] { Validator1, Validator2 }; // <-- error
            Validate(validators);
        }

        public static bool Validator1(string s)
        {
            return true;
        }

        public static bool Validator2(string s)
        {
            return true;
        }

        public static bool Validate(Func<string, bool>[] funcs)
        {
            return true;
        }
    }
OfirD
  • 9,442
  • 5
  • 47
  • 90
  • Until C# 10, lambdas and method groups don't have a natural type, so it has no delegate type to infer. – madreflection Jul 07 '22 at 12:49
  • @madreflection wasn't aware of that. But it sounds like something I should've found easily on SO, but I couldn't - so if you know of a dup, please share a link. – OfirD Jul 07 '22 at 12:52
  • I don't know of one, but I'll look for one. Fortunately, this is a language feature that doesn't require runtime support, so you can use C# 10 with .NET 4.7.2 (as long as you have the right tooling support installed, of course, like building in VS 2022) and it will compile that statement just fine. In fact, you can even use that feature when targeting .NET 2.0 if you were so inclined. It's *that* independent of the runtime. – madreflection Jul 07 '22 at 12:54
  • 1
    A simpler form of the problem, `var validator = Validator1;` would produce one of two messages. Prior to the .NET 6 SDK, you would get *"Cannot assign method group to an implicitly-typed variable"* and questions about that message often have to do with omitting the parentheses when trying to call the method. That wouldn't be too helpful. – madreflection Jul 07 '22 at 13:55
  • With the .NET 6 SDK, which knows about the fature, you get the mssage *"Feature 'inferred delegate type' is not available in C# . Please use version 10.0 or greater."* I didn't find anything useful by searching for that, and that even includes the feature *name*. So the more I think about it, the more I think it would *not* be easily found. – madreflection Jul 07 '22 at 13:55

0 Answers0