During the preparation for "Programing in C#" Certification from this book at objective 2.1 where the following code is shown for generic types:
class MyClass<T> where T : class, new()
{
public MyClass()
{
MyProperty = new T();
}
T MyProperty { get; set; }
}
I know what generic type is and why we need it, but can any one explain this confusing code and how we can use this with any example.
I guess you don't understand this part:
This says that
T
must be a reference type (i.e. class) and it must have a default constructor (a constructor with no arguments). This means thatT
can't beint
because it is a struct. It also can't beStreamReader
because it does not have a default constructor.Why is this useful?
Some things can only be used with reference types but not value types e.g.
as
. And because you saidT
must have a default constructor, you can do this:Since
T
must have a default constructor, you can callnew T()
.