jayatubi
jayatubi

Reputation: 2202

C# can't infer type argument type from usage when using Action

Suppose I have such code with MonoDevelope targeting .Net 3.5:

public void TestTemplate<T>(Action<T> action)
{
    // pseudocode
    m_funcDict[typeof(T).GetHashCode()] += action;
}

public void TestUsage(object arg)
{
    TestTemplate(TestUsage);
}

And I get such error:

Error CS0411: The type arguments for method `TestTemplate(System.Action)' cannot be inferred from the usage. Try specifying the type arguments explicitly (CS0411) (Assembly-CSharp)

Is there any way I could do this without manual specify the type argument?

What I want is just to automatically deduce the type.

Upvotes: 0

Views: 922

Answers (1)

Umair M
Umair M

Reputation: 10720

Is there any way I could do this without manual specify the type argument?

Shortest answer is NO, you cant.

Type inference doesn't work like this. You need to convert the method TestUsage to appropriate Action type in order to use it as parameter for TestTemplate.

However in your case you can use GetType() to extract Type from the argument at run-time and use it to access the desired item in dictionary.

public void TestTemplate(Action<object> action,Type t)
{
    // pseudocode
    m_funcDict[t.GetHashCode()] += action;
}

public void TestUsage(object arg)
{
    Type t = arg.GetType();
    TestTemplate(TestUsage,t);
}

Hope it helps

Upvotes: 1

Related Questions