A lot of statements (often seen in Linq) use TSource when it isn’t required for either compilation or execution. Why would you specify TSource?
Example:
List<int> list = new List<int>(5) { 0, 1, 2, 0, 3 };
int x = list.Where<int>(i => i == 0).FirstOrDefault<int>();
int y = list.Where(i => i == 0).FirstOrDefault();
How do the statements differ?
In both of your LINQ statements the
TSourcetype is required.It is just explicitly provided in the first statement and implicitly inferred in the second.
You would specify
TSourcein circumstances where the compiler cannot infer the type – often when the lambda is nested and very complicated.Also, if you wanted the operation to be performed using a supertype of type used in the lamdba. For example, you might specify the
Fruittype rather than let it inferAppleifAppleinherits fromFruit.Finally, you may choose to specify (or not) the
TSourcejust to make your code more readable – either by explicitly including the type or by removing redundant type repetition.