4

My eventual aim is to get a function that can take any other function - eg something like

      void RegisterHandler( Delegate function);

however - I want to be able to call it without doing any casting, or without type parameters - obviously Delegate doesn't work. If I declare:

      void RegisterHandler<T>( Func<T> function );

then it works fine - this works:

      string Whatever() {return "hi";}
      ...
      RegisterHandler( whatever );

however - as soon as I throw in parameters, it doesn't work

      void RegisterHandler<TParam1,TReturn>( Func<TParam1, TReturn> function );
      string Something( int x ) {return x.ToString();}
      ...
      RegisterHandler( Something );               //  doesn't compile - wants types specified
      RegisterHandler<int,string>( Something );   // works, but is what I'm trying to avoid

I'd even be ok if "object" worked - this is just part of a fluent interface, and I just want to be able to call it. I read somewhere that the number of parameters has to be >= the number of template types, and I guess the return type is counted, so I can never fulfill that.

Bottom line - I can't find any c# signature that will accept any function that takes one parameter, and returns something. Is it possible?

6
  • 1
    any function that takes one parameter, and returns something but this a Func<T, TResult> Apr 22, 2020 at 21:17
  • 1
    I don't believe C# allows you to do it as simple as you want it to be. Apr 22, 2020 at 21:18
  • 7
    You say you want to take any function but also that you want to be able to call it -- ok, if I hand you a delegate to int M(void* px, out string y), how exactly are you planning on calling it? What does the call site look like? That's a function, you said you wanted to take any function, so what are you going to do with it? Apr 22, 2020 at 21:19
  • 1
    My point here is: the C# type system essentially requires you to provide a proof that the operations you're doing are safe, and "call any function however I choose" is inherently unsafe, so it's going to be a little tricky to get what you say you want. I suspect that you actually have far more stringent requirement than "any function whatsoever"; by understanding what those restrictions are, you can better see how to use the type system to work with you. Apr 22, 2020 at 21:22
  • 1
    Also, your question is a little confusing because you start by saying "any function" and end by saying "any function of one parameter with a non-void return type", and those are two very different things. Are you saying "my goal is actually any function of one parameter with a non-void return type"? or are you saying "my goal is any function at all, but I can't even get this simpler case working?" Apr 22, 2020 at 21:25

2 Answers 2

15

Rather than attacking your problem directly, which needs some clarification, let me address your concerns here:

I read somewhere that the number of parameters has to be >= the number of template types

Let's crisp that up a bit.

First off, those are generic type parameters, not "template types". This isn't C++. Generics are similar to templates but they are not templates, and the sooner you stop thinking of them as templates, the better.

It is NOT true that the number of formal parameters needs to be greater than or equal to the number of generic type parameters declared by the generic method. For example:

static void M<K, V>(Dictionary<K, V> d) { }
...
Dictionary<int, string> d = whatever;
M(d); // No problem!

The number of formal parameters is one, the number of generic type parameters is two, but we have no problem doing type inference here.

The real rule is quite a bit more complicated. Rather, the real problem that you're running into is:

The conversion of a method group to a delegate requires that the parameter types of the delegate be known before the conversion happens.

Let's suppose we have:

int F(string x) { ... }
void M<A, R>(Func<A, R> f) { ... }
M(F);

What happens? We must determine what F means when converted to Func<A, R> but we know neither A nor R. How do we determine the meaning? We do overload resolution. That is, we would pretend that there was a call:

A a = whatever;
F(a)

and ask "which method named F would work?"

But we never even get to that step because we don't know what A is yet. Type inference fails to make progress. Now, if by contrast you had:

int F(string x) { ... }
void M<A, R>(A a, Func<A, R> f) { ... }
M("abc", F);

Now type inference first says "I deduce from the use of "abc" for a that A is string." After that inference is made, now overload resolution would succeed. If we did

string a = whatever;
F(a);

then overload resolution would determine that F means int F(string).

Once we have determined that F means int F(string), now we can ask the question "what can we deduce about the conversion from int F(string) to Func<string, R>, and from that we deduce R must be int and we're done.

I know what you're going to ask next. I only have one overload called F, so why don't we just pick it automatically?

There are many problems with making exceptions like that. First, special cases tend to multiply, and soon we have an even crazier inference algorithm that no one understands and it cannot be changed without causing bugs. Second, it makes your code brittle; it means that inference depends on the number of accessible methods named F in scope. Suppose you add a new private method also called F; does inference suddenly change?

No, the rule is straightforward and understandable once you know it. Method groups are resolved exactly the same as though there was a call to the method. But we cannot simulate a call until after the argument types are inferred.

Believe me, I know as well as anyone how tricky the type inference algorithm can be in C#; it has a lot of these sorts of surprising cases. If you have a more crisp question about the design, implementation or specification of this algorithm feel free to open up a new question and leave me a comment on this answer and I will try to have a look.

1
  • 2
    thanks Eric - as always - your explanations are amazing. What you've said makes sense - unfortunately - I was going in this direction purely to make the code look cleaner/simpler, and adding type parameters sort of destroys that :( Apr 23, 2020 at 0:09
1

Are... you looking for Action?

Func<T> is a .net delegate that is meant to return a value.

Action is a .net delegate that does not return a value

Action<T> also accepts up to 16 params.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.