13

Is there any reason for the use of 'T' in generics? Is it some kind of abbreviation? As far as I know, everything works. For example

public G Say<G>(){ ... }

or even

public Hello Say<Hello>(){ ... }
thinkbeforecoding
  • 6,668
  • 1
  • 29
  • 31
Sorskoot
  • 10,190
  • 6
  • 55
  • 98
  • Asked here [what-does-t-mean-in-c?](http://stackoverflow.com/questions/400314/what-does-t-mean-in-c?lq=1) too. – nawfal Jan 17 '14 at 13:32

8 Answers8

33

T is for Type. But it's really just a tradition and there is nothing to prevent you from using other names. For example, generic dictionaries use <TKey, TValue>.

There is also a Microsoft guideline that recommends using the letter T if you have a single type parameter, and prefix descriptive parameter names with T if you have more than one. Doing so will provide a more consistent feel across your code.

Vilx-
  • 104,512
  • 87
  • 279
  • 422
8

T for Type, as like you said everything works fine.But putting T in that place remind you that is of generic type.

yesraaj
  • 46,370
  • 69
  • 194
  • 251
7

It's just a shorthand like I is conventionally used for interfaces in .NET, and in other environments C is sometimes used for classes (Delphi uses this, IIRC).

Generally "T" on its own means "the single type parameter in this context" and if you have multiple type parameters, they get a T prefix, e.g. Dictionary<TKey, TValue>. It just makes it obvious when you're reading the code that it's a type parameter rather than a specific concrete type.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

oh, I would have thought T for Thing :)

Joel in Gö
  • 7,460
  • 9
  • 47
  • 77
2

There might also be a bit of tradition too as C++ templates use T most of the time, and generics are similar in function to C++'s templates, when used for generic programming.

Robert Gould
  • 68,773
  • 61
  • 187
  • 272
1

If your generic type represents something special, you can make it more precise.. Usually prefixing it with T : IRepository<TEntity>, SomeCollection<TItem, TComparer> ..

thinkbeforecoding
  • 6,668
  • 1
  • 29
  • 31
0

T for Type

Also, E is used for Element that's very common too. You're right G also works.

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
0

I thought that was T for Template because it first appears in C++.

Nicolas Dorier
  • 7,383
  • 11
  • 58
  • 71