Search code examples
c#type-inferencetype-parameter

How can I get this method to infer type argument from usage?


I would like to get TryGet method to infer the type argument, just as it is possible for TrySet:

private void Test()
{
    TryGet<int>(RefProperty, s => s.GetInt); // works fine

    TryGet(RefProperty, s => s.GetInt); // CS0411 here

    TrySet(RefProperty, s => s.SetInt, 1234);
}

private T TryGet<T>(int property, Expression<Func<Material, Func<int, T>>> expression)
{
    return Material.HasProperty(property) ? expression.Compile()(Material)(property) : default;
}

private void TrySet<T>(int property, Expression<Func<Material, Action<int, T>>> expression, T value)
{
    if (Material.HasProperty(property))
    {
        expression.Compile()(Material)(property, value);
    }
}

Here are the signatures of GetInt and SetInt in Material:

int GetInt(int);

int GetInt(string);

void SetInt(int, int);

void SetInt(string, int);

Is this possible somehow or am I asking the compiler too much?


Solution

  • Because TryGet inherently returns a value, it makes sense to choose the value to return:

    private void Test()
    {
        TryGet(RefProperty, s => s.GetInt, 42);
    }
    
    private T TryGet<T>(int property, Expression<Func<Material, Func<int, T>>> expression, T defaultValue)
    {
        return Material.HasProperty(property) ? expression.Compile()(Material)(property) : defaultValue;
    }
    

    Problem solved.