What does T mean: type name?

I see the code so many times:

public class BaseList<T> : List<T> where T : BaseBE 

My question is what this code means and why do we write this line as follows? I know that it uses List<T> , but what's the point of where T : BaseBE ?

+4
source share
2 answers

This where T:BaseBE is a limitation of what T may be. In this particular case, it tells you that T can be of type BaseBE or any class that inherits it, but nothing more.

For more information you can check the MSDN , you will find much more details and examples.

+8
source

This means that the generic type T must inherit from BaseBE, this is called a type constraint. This allows you to use type T as a BaseBE in a BaseList.

So for example:

 class Foo { } BaseList<Foo> myList; // Wont compile, Foo is not a BaseBE class Bar : BaseBE { } BaseList<Bar> myOtherList; // Ok Bar is a BaseBE 

Here you can read about other types of restrictions:

http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.80).aspx

For example, if T: new () means that T must have an open constructor with no parameters.

+3
source

Source: https://habr.com/ru/post/1488342/


All Articles