Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does where T : name of type mean? [closed]

Tags:

c#

I see code like this many times:

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

My question is what is meaning of this code and why do we write this line like this? I know it is using List<T> but what is the meaning of where T : BaseBE?

like image 722
Azad Chouhan Avatar asked Dec 21 '22 03:12

Azad Chouhan


2 Answers

This statement where T:BaseBE is a constraint over what T can be. In this specific case, it's telling you that T can be of type BaseBEor from any class inheriting from it, but nothing else.

For more details you could check MSDN, you'll find much more details and examples.

like image 58
Claudio Redi Avatar answered Jan 16 '23 19:01

Claudio Redi


It means that the generic type T must inherit from BaseBE, this is called a type constraint. This allows the type T to be used as a BaseBE within 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

You can read about more types of constraint here:

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

E.g where T : new() means T must have a public parameterless constructor.

like image 26
paulm Avatar answered Jan 16 '23 18:01

paulm