-2

Although I've looked through several of the answers regarding this question, I'm still not sure if I know what this line of code is doing:

public class SomeClass<P> : SomeInterface where P : AnotherInterface, new(){...}

What is new() doing?

Mark S
  • 103
  • 2
  • 8

1 Answers1

1

While you usually see where T : Whatever[, Whatever2] refer to other interfaces and classes, it can also be one of any of these constraints:

  • where T : struct - T has to be a value type
  • where T : class - T has to be a reference type
  • where T : unmanaged - T and all of its variables have to be value types, as well as the variables those value types have... etc.
  • where T : new() - T has to have a parameterless constructor. This constraint must be specified last.
  • where T : U - T must be or derive from the argument supplied for U
Powerlord
  • 87,612
  • 17
  • 125
  • 175
  • In case you're wondering, yes this allows you to call `new T()` in your interface's code (or `new P()` in your example). – Powerlord Sep 21 '18 at 00:47
  • Excellent! Thank you! The [constraints](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters) you refer to really explain it nicely. @Powerford - yeah,I should have used T instead of P... – Mark S Sep 21 '18 at 04:22