Generics: when to use new () as a restriction of type parameters?

The type argument must have an open constructor without parameters. When used in conjunction with other restrictions, the new () constraint must be specified last.

Can you guys give me an example scenario when this limitation is needed?

+3
source share
3 answers

Basically this limitation new()comes down to:

class Factory<T> where T : new()
{
    public T Create()
    {
        return new T();
        //     ^^^^^^^
        //     this requires the new() type constraint.
    }
}

Now you are not allowed to pass arguments to the constructor. If you still want to initialize a new object, you can achieve this, for example. introducing another restriction:

interface ILikeBananas
{
    double GreenBananaPreferenceFactor { get; set; }
}

class Factory<T> where T : ILikeBananas, new()
{
    public T Create(double greenBananaPreferenceFactor)
    {
        ILikeBananas result = new T();
        result.GreenBananaPreferenceFactor = greenBananaPreferenceFactor;

        return (T)result;
        //     ^^^^^^^^^
        //     freely converting between ILikeBananas and T is permitted
        //     only because of the interface constraint.
    }
}

, Activator.CreateInstance, , , .

Activator.CreateInstance new(); .

+9

-. -.

, , . - , , , . where T : new(), return new T();.

, , Func<T> . , , . , new T() .

+1

I will just write with a simple example. I created a method:

public T GetFromXml<T>(string xml)
    where T: class, new()
{
    if (String.IsNullOrEmpty(xml))
    {
        return new T();
    }
    return xml.AsObjectFromXml<T>();
}

And use it as follows:

Phones = GetFromXml<List<PhoneData>>(source.Phones);

Because I prefer empty collections by null values.

0
source

Source: https://habr.com/ru/post/1764303/


All Articles