I have the following extension method which asserts that a property (Id) contains a specified attribute (TV):
public static void ShouldHave<T, TV, TT>(this T obj, Expression<Func<T, TT>> exp) {...}
The method can be called like this:
MyDto myDto = new MyDto();
myDto.ShouldHave<MyDto, RequiredAttribute, int>(x => x.Id);
Compiles just fine. I was wondering if it is possible to remove T and TT from the method signature. T because ShouldHave is called on T why it shouldn’t be necessary to specify it explicitly. And TT is the type of the property referenced in the expression (x.Id).
Automatic inference of type arguments only works if no generic arguments are specified in the method call. I.e., this:
is not valid syntax. You can either have “all or nothing”.
Thus, if you want to infer
TandTT, you need to pass the information currently contained inTVin some other way. For example, one option would be to pass the type of the attribute as a parameter:(Obviously, this will require changes in your implementation of ShouldHave).
Then you should be able to call the method like this: