StackOverflowException: The requested operation caused a stack overflow. While adding object to list

Viewed 58

I've writen void that returns List<> of objects. But it crashes with:

StackOverflowException: The requested operation caused a stack overflow. System.Collections.Generic.List'1[T].set_Capacity (System.Int32 value) (at <6073cf49ed704e958b8a66d540dea948>:0) System.Collections.Generic.List'1[T].EnsureCapacity (System.Int32 min) (at <6073cf49ed704e958b8a66d540dea948>:0) System.Collections.Generic.List'1[T].AddWithResize (T item) (at <6073cf49ed704e958b8a66d540dea948>:0)

Here is my code:

public List<Object> MyObjects;

public List<Object> AllObjectsExcluding(string excludedObjectId)
    {
        List<Object> objects = new List<Object>();

        foreach (Object object in MyObjects)
        {
            if (object.id != excludedObjectId)
            {
                objects.Add(object); //StackOverflowException
            }
        }

        return objects;
    }

public class Object
    {
        public string id;
    }
2 Answers

First of all in general do not use Object as name for your own type!

It is already confusing enough having both System.Object, the implicit mother type of everything in c# and UnityEngine.Object, the mother type of all asset like references in Unity.


Further there is a type alias object (== System.Object)

=> The code you show us here wouldn't even compile at all as object (and any other built-in keyword and type alias) is not allowed as variable names.


Finally, as mentioned in the comments, the code you show us (besides before mentioned compiling issues) wouldn't produce that exception => It has to be something else you haven't shown us.


For your use case you would be better simply using Linq Where

using System.Linq;

...


return MyObjects.Where(obj => obj.id != excludedObjectId).ToList();

In my case example function was also called by some recursive function. Thanks JonasH!

Related