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
Tmust be a reference type (i.e. class) and it must have a default constructor (a constructor with no arguments). This means thatTcan't beintbecause it is a struct. It also can't beStreamReaderbecause 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 saidTmust have a default constructor, you can do this:Since
Tmust have a default constructor, you can callnew T().