DEV Community

Ricky Stam
Ricky Stam

Posted on • Edited on

12 6

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 ❤️

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
ahedreville profile image

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay