DEV Community

Ricky Stam
Ricky Stam

Posted on • Updated on

C# Create new T()

For a long time now whenever i had to create a new instance of a generic type parameter i was using Activator.CreateInstace(Type) method
https://msdn.microsoft.com/en-us/library/wccyzw83.aspx

Example:

public class Dog : ISound
{
    public string Sound { get; set; } = "woof woof";
}

public class Animal<T> where T : ISound
{
    public ISound GetInstance()
    {
        return (ISound)Activator.CreateInstance(typeof(T));
    }
}
Enter fullscreen mode Exit fullscreen mode

Recently i stumbled upon the new constraint keyword from the MS docs (somehow i missed that 😞)
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint
and the Generic class of Animal above can be rewritten as following:

public class Animal<T> where T : ISound, new()
{
    public T GetInstance()
    {
        return new T();
    }
}
Enter fullscreen mode Exit fullscreen mode

and can be used:

var animal = new Animal<Dog>();
var dog = animal.GetInstance();
var sound = dog.Sound; //woof woof
Enter fullscreen mode Exit fullscreen mode

Important: When you use the new() constraint with other constraints, it must be specified last.

This post was written with love ❤️

Top comments (1)

Collapse
 
ahedreville profile image
Alexandre Hedreville • Edited

the drawback for this is that you need to have no constructors or a public parameter less constructor