Question

After rewriting my event invocation function to handle the events and their arguments generically, I started going over my code (to match the change), and I noticed that the compiler implicitly made the generic call.

Here's my function:

private void InvokeEvent<TArgs>(EventHandler<TArgs> invokedevent, TArgs args) 
    where TArgs : EventArgs
    {
        EventHandler<TArgs> temp = invokedevent;
        if (temp != null)
        {
            temp(this, args);
        }
    }

and here is the line to call the function:

InvokeEvent(AfterInteraction, result);

This compiles without a problem, and the intellisense even display the "correct" call (with the part).

Is this a compiler feature (the generic type can, actually, be directly inferred from the second argument), or am I going crazy over nothing and missing the point?

Was it helpful?

Solution

If the compiler can infer all type parameters then you don't need to specify them explicitly. In this case it can infer TArgs from the second parameter.

But if it can't infer all type parameters, you need to specify all of them, even the ones the compiler could infer.

OTHER TIPS

It is call type inference, read about it here, search for the chapter "Type Inference"

As you have said the compiler has inferred type from the second argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top