Generics in .net 2.0 : Using a Where class on a class definition

73 views Asked by At

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.

1

There are 1 answers

3
Sweeper On BEST ANSWER

I guess you don't understand this part:

where T:class,new()

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 that T can't be int because it is a struct. It also can't be StreamReader 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 said T must have a default constructor, you can do this:

public MyClass()
{
    MyProperty = new T();
}
T MyProperty { get; set; }

Since T must have a default constructor, you can call new T().