Home > Blockchain >  Adding a generic type to a List?
Adding a generic type to a List?

Time:02-14

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.

CodePudding user response:

I don't think this is a noob question because I had a hard time to get used to generics myself.

You have not been to far away from the answer. The missing part it to restrict the type T to only allow objects with a base constructor. This is done with where.

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());//Error Here
            if (list.Count > resolution)
                list.RemoveAt(list.Count - 1);
        }
        yield return null;
    }

Best regards Stefan

  • Related