Sometimes you want to limit the types that can be used in a generic. You can do that using constraints:
where T : class
where T : struct
where T : new()
where T : SomeBaseClass
SomeBaseClass
where T : SomeInterface
SomeInterface
public class MyClass<T> where T : class, new() { public T CreateInstance() { return new T(); } } // Usage var myClass = new MyClass<MyType>(); // Assuming MyType is a class with a parameterless constructor
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: