2

i want to understand that code. I think T must be IContinentFactory's implemented class but i don't understand to end of the new() keyword.

class AnimalWorld<T> : IAnimalWorld where T : IContinentFactory, new()
{
.....
}
altandogan
  • 1,245
  • 6
  • 21
  • 44
  • 8
    [MSDN](http://msdn.microsoft.com/en-us/library/sd2w2ew5(v=vs.110).aspx) – Tim Schmelter Feb 17 '13 at 19:39
  • (There is no generic interface here and the other interfaces are just noise around the real question.) –  Feb 17 '13 at 20:15
  • As a subtlety to consider with the answers given: `struct`s also satisfy the `new()` constraint. It is an interesting question as to whether `struct`s actually have a public parameterless constructor - and IIRC the C# and CLI specifications disagree on this question: but crucially: `struct`s always satisfy this constraint. – Marc Gravell Feb 17 '13 at 20:32
  • Does this answer your question? [What does new() mean?](https://stackoverflow.com/questions/4236854/what-does-new-mean) – Heretic Monkey Mar 30 '22 at 12:31

4 Answers4

6

T: new() means that type T has to have a parameter-less constructor.

By that you actually specify that you can write T param = new T(); in your implementation of AnimalWorld<T>

eyossi
  • 4,230
  • 22
  • 20
  • +1 Only answer to mention that the constraint allows code which uses `T` to do something it otherwise could not. – supercat Feb 18 '13 at 17:14
5

new() mean that T must have default(parameterless) ctor.

Constraints on Type Parameters (C# Programming Guide)

Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
4

The constraint new() means that the type T must have a public parameterless instance constructor. This includes all value types, but not all classes. No interface or delegate type can have such a constructor. When the new() constraint is present, T can never be an abstract class.

When new() is present, the following code is allowed inside the class:

T instance = new T();
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
3
class AnimalWorld<T> : IAnimalWorld where T : IContinentFactory, new()

Here is what the declaration means:

  • AnimalWorld is a class with a generic type parameter T
  • The class AnimalWorld must implement IAnimalWorld
  • The type parameter T must implement IContinentFactory
  • The class for the type parameter T must have a no-argument constructor (that's what the new is for).
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523