What does "T" mean in C#?

I have a VB background and I'm converting to C# for my new job. I'm also trying to get better at .NET in general. I've seen the keyword "T" used a lot in samples people post. What does the "T" mean in C#? For example:

public class SomeBase<T> where T : SomeBase<T>, new()

What does T do? Why would I want to use it?

88200 次浏览

It means "any class". It could be "B", "A", whatever. I think T is used because of "Template"

T is not a keyword per-se but a placeholder for a generic type. See Microsoft's Introduction to Generics

The equivalent VB.Net syntax would be:

Public Class SomeBase(Of T As {Class, New}))

Best way would be to get yourself familiar with "Generics", many resources on the web, here's one

T is not a keyword but a name, could be anything really as far as I know, but T is the convention (when only one type is needed, of coruse)

It's a symbol for a generic type parameter. It could just as well be something else, for example:

public class SomeBase<GenericThingy> where GenericThingy : SomeBase<GenericThingy>, new()

Only T is the default one used and encouraged by Microsoft.

A good example of another name used instead of T would be the hash table classes, e.g.

public class Dictionary<K,V> ...

Where K stands for Key and V for value. I think T stands for type.

You might have seen this around. If you can make the connection, it should be fairly helpful.

The T is the name for the type parameter in a generic class. It stands for "Type" but you could just as well call it "Alice."

You use generics to increase reusability in a type-safe manner without needlessly duplicating code. Thus, you do not need to write classes for ListOfIntegers, ListOfStrings, ListOfChars, ListOfPersons and so on but can instead write a generic class List<T> and then instantiate objects of types List<Int32>, List<string>, List<char> and List<Person>. The compiler does the work for you.

That would be a "Generic". As people have already mentioned, there is a Microsoft explanation of the concept. As for why the "T" - see this question.

In a nutshell, it allows you to create a class/method which is specialized to a specific type. A classical example is the System.Collections.Generic.List<T> class. It's the same as System.Collections.ArrayList, except that it allows you to store only item of type T. This provides type safety - you can't (accidentally or otherwise) put items of the wrong type in your list. The System.Collections.Generic namespace contains several other different collection types which make use of this.

As for where you could use it - that's up to you. There are many use-cases which come up from time to time. Mostly it's some kind of a self-made collection (when the builtin ones don't suffice), but it could really be anything.