Search code examples
c#stack-overflowrecursion

how can i get catch the root of a stackoverflow exception on recursive code


I have the following recursive code and i am getting a stackoverflow exception. I can't figure out the root cause because once i get the exception,i dont get the full call stack in Visual studio.

The idea is that there are org teams that roll up into larger "Main" teams.

Does anyone see a flaw on this code below that could be the culprit?

    private Unit GetUnit(Unit organisationalUnit)
    {
        if (organisationalUnit.IsMainUnit)
        {
            return organisationalUnit;                
        }

        if (organisationalUnit.Parent == null)
            return null;

        return GetUnit(organisationalUnit.Parent);
    }

Solution

  • Does the root always have Parent == null? Tried checking

    if (organisationalUnit.Parent == organisationalUnit)
        return null;
    

    ?