Home > Net >  Type <T> notation
Type <T> notation

Time:08-18

I'm new to C# and programming in general and wondering about the notation <T>

The question has been asked before, for example here: What does "T" mean in C#?

I just wanted to get some clarification to extend on that.

Can <T> be anything? I understand it is a naming convention by MS and could be named whatever you want, and it is for generic types, int, bools or whatever - but can it extend beyond that?

Can I pass an entire function/method to it just for the sake of it? Or is it strictly for return types if that makes sense?

CodePudding user response:

Generic parameters, specified using the <> notation indicate the type. It is up to the defining class whether or not to limit the types that can be supplied. For example you could have a base class

public class Animal
{}

and a several derived classes

public class Dog : Animal
{}

public class Cat : Animal
{}

You could then make human a class like this

public class Human
{
  public void AddPet<T>() where T: Animal
  {}
}

In this case the T is constrained to be only things that inherit from Animal

So, you could do this

var me = new Human();
me.AddPet<Dog>();

but not this

var me = new Human();
me.AddPet<Human>();

CodePudding user response:

This is a way of declaring new types/classes that can use another type inside initially not defined. But whenever you instantiate new object of that class, you can to specify that type and it will only be used for that object.

In short each of object of that class might have different type for that value on instantiation.

public class Test<T>
{
    public T a;
}

This is a generic class where the type of a isn't known at this stage, but let's see example objects instantiations of that class:

var obj1 = new Test<int>(); // a will be of type int
var obj2 = new Test<List<string>>(); // a will be a list of strings

Type is dependent on object instantiation...

Update: Check docs for more details about generics https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-classes

CodePudding user response:

T represents generic type. It could be any type (user/system defined).

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic?view=net-6.0

Please mark this answer, if it is useful to you.

  •  Tags:  
  • c#
  • Related