Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in C#, what does where T: new() mean? [duplicate]

Possible Duplicate:
What does new() mean?

Like in title. I wonder what this syntax in the code means. I've find it in some samples but it wasn't explained and I don't really know what it does.

public class SomeClass<T> where T: new()  // what does it mean?

Can anyone explain that for me?

like image 673
Harry89pl Avatar asked Dec 13 '22 04:12

Harry89pl


1 Answers

Perhaps you mean you saw something along these lines?

public class SomeClass<T> where T: new() 
{...}

which means that you can only use the generic class with a type T that has a public parameterless constructor. These are called generic type constraints. I.e., you cannot do this (see CS0310):

// causes CS0310 because XmlWriter cannot be instantiated with paraless ctor
var someClass = new SomeClass<XmlWriter>();

// causes same compile error for same reason
var someClass = new SomeClass<string>();

Why would you need such constraint? Suppose you want to instantiate the a new variable of type T. You can only do that when you have this constraint, otherwise, the compiler cannot know beforehand whether the instantiation works. I.e.:

public class SomeClass<T> where T: new() 
{
    public static T CreateNewT()
    {
         // you can only write "new T()" when you also have "where T: new()"
         return new T();
    }
}
like image 198
Abel Avatar answered Feb 03 '23 21:02

Abel