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
?
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 BaseBE
or from any class inheriting from it, but nothing else.
For more details you could check MSDN, you'll find much more details and examples.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With