Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid generic arguments

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).

like image 687
ThomasArdal Avatar asked May 30 '26 23:05

ThomasArdal


1 Answers

The following compiles:

public static void ShouldHave<T, TT>(this T obj, Expression<Func<T, TT>> exp)
{...}

MyDto myDto = new MyDto();
myDto.ShouldHave(x => x.Id);

This omits the TV type argument, which is the reason for your need to explicitly specify the generic arguments at the call site. If you need this argument then you’re out of luck.

like image 78
Konrad Rudolph Avatar answered Jun 01 '26 11:06

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!