Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does angle brackets do on class names in C#?

I know how you can use List<T> for example and decide what that collection is holding. That's where T comes in. But I'm not sure I understand the brackets fully.

If I create a class...

class MyClass<int> { }

Or instead of int I could use T or object or string or whatever. What does that mean? Does it turn into a collection automatically?

like image 830
user2413912 Avatar asked Sep 13 '25 08:09

user2413912


1 Answers

Generic classes allow class members to use type parameters. They are defined in the same way as generic methods, by adding a type parameter after the class name.

class Point<T>
{
  public T x, y;
}

To instantiate an object from the generic class the standard notation is used, but with the type argument specified after both class names. Note that in contrast to generic methods, a generic class must always be instantiated with the type argument explicitly specified.

Point<short> p = new Point<short>();

Reference: http://www.pvtuts.com/csharp/csharp-generics

like image 51
Krupa Patel Avatar answered Sep 15 '25 23:09

Krupa Patel