valentin sorlin
valentin sorlin

Reputation: 33

I want instanciate a Generic type in C# unity3D

Hello i tried to Resize a generic tab but my probleme is to initialise new element

    List<T> Resize<T>(List<T> list, int sz)
{
    if (list.Count < sz)
    {
        while (list.Count < sz)
        {
            T someInstance = new T(); // this line is the probleme
            list.Add(someInstance);
        }
    } else if ((list.Count > sz))
    {
        list.RemoveRange(sz, list.Count);
    }
    return list;
}

Thank you <3

Upvotes: 2

Views: 41

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

you need the generic constraint new() on your definition of T:

List<T> Resize<T>(List<T> list, int sz) where T: new()

Of course this assumes that every type has a parameterless constructor. ...

Upvotes: 1

Related Questions