Search code examples
c#genericsimplicit-typing

C# Compiler feature or am I loosing my mind?


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?


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.