How to change from which argument is the type inferred in generic methods?

Suppose there's a static method in my Utils class, that sets the value of a property.

public static SetPropertyValue<TDest, TVal>
    (Expression<Func<TDest, TVal>> expression, 
     TDest destination, 
     TVal value) 
{ 
    // ...
}

Additionally, there is a class:

public class DataObject { public short Code { get; set; } }

And the usage code:

DataObject obj = new DataObject();
int code = 404;
Utils.SetPropertyValue(m => m.Code, obj, code);

When the above code is run, the expression is changed to m => Convert(m.Code) because the third parameter given is an integer and the expression expects the short. That means that the type inference system decided to prefer the third argument to determine the TVal type.

I wish this method's third argument (value) to be restricted to the type defined by the first argument (expression). Is this possible? If yes, how?

Jon Skeet
people
quotationmark

No, you can't affect type inference that way - and if it did infer TVal as short, your code wouldn't compile, because there's no implicit conversion from int to short.

Surely the best solution is just to avoid using two different types to start with:

short code = 404;
Utils.SetPropertyValue(m => m.Code, obj, code);

Now the types will be inferred properly, and there won't be any conversions.

people

See more on this question at Stackoverflow