0

This is probably a noob question, so sorry in advance for my inexperience...

So I have a list with thousands of elements which fluctuates frequently, so I created this Coroutine to update it without creating a whole new list and populating it every time it changes...

    public static IEnumerator ListSetup(List<Vector3> list, int resolution)
    {
        while (list.Count != resolution)
        {
            if (list.Count < resolution)
                list.Add(new Vector3());
            if (list.Count > resolution)
                list.RemoveAt(list.Count - 1);
        }
        yield return null;
    }

...and it works a treat.

Then, I wanted to modify it so that it can take any type of list, not just Vector3's, but I have been having some trouble with the syntax..

    public static IEnumerator ListSetup<T>(List<T> list, int resolution)
    {
        while (list.Count != resolution)
        {
            if (list.Count < resolution)
                list.Add(new T());//Error Here
            if (list.Count > resolution)
                list.RemoveAt(list.Count - 1);
        }
        yield return null;
    }

I've tried typeof(T), GetType(T), typeof(T).MakeGenericType(), Add(T), and tons of other variations, but it is clear that I just don't understand how Types and Generics work.

Any help would be appreciated.

derHugo
  • 83,094
  • 9
  • 75
  • 115
FaffyWaffles
  • 125
  • 1
  • 7
  • You need to add the following generic constraint `where T : new() `. See the [docs](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters) for different options – Matt Feb 13 '22 at 07:38

1 Answers1

2

You have not been to far away from the answer. The missing part is to restrict the type T to only allow objects with a public parameter-less constructor.

This is done with the generic type-constraint where and the new-constraint

public static IEnumerator ListSetup<T> (List<T> list, int resolution) where T : new()
{
    while (list.Count != resolution)
    {
        if (list.Count < resolution)
            list.Add(new T());
        if (list.Count > resolution)
            list.RemoveAt(list.Count - 1);
    }
    yield return null;
}
derHugo
  • 83,094
  • 9
  • 75
  • 115