4

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?

Community
  • 1
  • 1
Harry89pl
  • 2,415
  • 12
  • 42
  • 63

3 Answers3

9

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();
    }
}
Abel
  • 56,041
  • 24
  • 146
  • 247
  • 1
    thats the answer :) thanks a lot :) now everythink clear:) – Harry89pl Mar 23 '12 at 15:51
  • `new SomeClass()` causes an error (it doesn't “throw”), simply because `string` has no parameterless constructor. – svick Mar 23 '12 at 16:15
  • @svick: that's precisely what I meant, I'll remove "throws". CS0310 is a compile time error. The cause was already in my text, I thought. – Abel Mar 23 '12 at 17:56
  • @Abel, I thought it confused you, because I read “also throws for **some** reason”. Now I noticed that's not what you wrote, my bad. – svick Mar 23 '12 at 18:08
3

It is a generic type constraint, meaning the generic type must have a public parameterless constructor.

Your code example will not even compile.

The correct syntax is:

SomeClass<T> where T : new()
Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

You haven't posted the full line of code since that won't compile, but it is a constraint in generics. Here is the MSDN article.

Bryan Crosby
  • 6,486
  • 3
  • 36
  • 55