Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is TSource in C# .NET?

Tags:

Question

What is TSource?

Here is an example from MSDN:

public static IEnumerable<TSource> Union<TSource>(
    this IEnumerable<TSource> first,
    IEnumerable<TSource> second,
    IEqualityComparer<TSource> comparer
)

Is it a type? Couldn't find any MSDN documentation on it. I assume it can't be a type since I couldn't click on it in .NET Reflector.

Is it a .NET keyword? Didn't find it in the C# keywords list.

Is it something the .NET compiler interprets in a special way?

What I already know

I know that T is a generic type parameter which is used sort of as a placeholder in a generic method. Example from What Are Generics from MSDN:

public class Stack<T>
{
   T[] m_Items; 
   public void Push(T item)
   {...}
   public T Pop()
   {...}
}
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
int number = stack.Pop();
like image 706
Lernkurve Avatar asked Feb 20 '11 13:02

Lernkurve


1 Answers

TSource is just a generic type parameter. You can tell that because it comes in angle brackets after the method name in the declaration:

public static IEnumerable<TSource> Union<TSource>

You can use any identifier for a type parameter name, so this would be equally valid:

public static IEnumerable<Foo> Union<Foo>

Conventionally, however, either T or a name beginning with T is used. In this cases, it's indicating the type of the "source" element of the union. LINQ methods typically use the following type parameter names:

  • TSource: element type of the input (source)
  • TResult: element type of the output (result)
  • TKey: element type of a key used for things like grouping
  • TElement: element type of an intermediate sequence - this is more rarely used, but it appears in some overloads of GroupBy and similar methods
like image 100
Jon Skeet Avatar answered Sep 20 '22 15:09

Jon Skeet