views:

160

answers:

4

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();
     }
}
+2  A: 
myList = new string[0]

This should create an array with 0 elements.

EDIT: I just tested new string[] {} and it works for me. Maybe the reason for your stackoverflow is elsewhere.

Can you post the rest of your method? Generally spoken, stackoverflows occur specially when performing a high number recursive method calls. Like this:

void MyMethod(int i)
{
   MyMethod(i); //!StackOverFlow!
}
Simon
Nope, still getting StackOverflowException.
MCS
+8  A: 

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;
  }

}

Jonas H
+1 for recognizing the problem in this special case. Would be perfect if you wrote the correct usage of backing fields.
Simon
+1  A: 

It appears as though what @Jonas H said is accurate, you may be recursivly modifying the Property instead of its backing field.

WRONG

private String[] _myList;
public String[] myList 
{
    get {return _myList;}
    set  
    { 
        for (int i = 0; i < myList.Length; i++) 
        { 
            if (myList[i] != null) myList[i] = myList[i].Trim(); 
        } 
    }
}

RIGHT

private String[] _myList;
public String[] myList 
{
    get {return _myList;}
    set  
    { 
        for (int i = 0; i < _myList.Length; i++) 
        { 
            if (_myList[i] != null) _myList[i] = _myList[i].Trim(); 
        } 
    }
}
Nate Bross
+2  A: 

Your set code doesn't actually assign anything, and refers to itself. I have a feeling you're misunderstanding how properties work. You need a backing variable which the property manipulates:

private string[] _myList;

And then you need to have your set code work with that variable:

public string[] myList
{
    get
    {
        return _myList;
    }

    set 
    {
        _myList = value; // you have to assign it manually
        for (int i = 0; i < _myList.Length; i++)
        {
            if (_myList[i] != null) _myList[i] = _myList[i].Trim();
        }
    }
}

If you try and access myList, it's accessing itself, which then accesses itself, etc, leading to infinite recursion and a stack overflow.

Samir Talwar
Tested; I can say this is the most likely cause, if not THE cause.
BoltClock