Search code examples
c#arraysstack-overflow

Why does my array initialization code cause a StackOverflowException to be thrown?


The following line of code in my class constructor is throwing a StackOverflowException:

myList = new string[]{};  // myList is a property of type string[]

Why is that happening? And what's the proper way to initialize an empty array?


UPDATE: The cause was in the setter, in which I was attempting to trim all values:

set 
{
  for (int i = 0; i < myList.Length; i++)
     {
        if (myList[i] != null) myList[i] = myList[i].Trim();
     }
}

Solution

  • If myList is a property, did you check that the body of its setter does not recursively assign to itself instead of the backing field, as in:

    private string[] _myList;
    
    public string[] myList { 
      get { 
        return _myList; 
      }
      set { 
        _myList = value;
      }
    

    }