Search code examples
c#stack-overflow

C# - Property is causing StackOverflow


public class ModelInfo
{
    public int AssignedCount { get; set; }
    public int UnassignedCount { get; set; }
    public int TotalCount { get { return UnassignedCount + TotalCount; } }
}

*Edit:* I realized when I put this code in SO that the TotalCount property is adding the UnassignedCount + the TotalCount (I meant to add the other two counts together). Can someone please provide a throughough explanation on why the SO error occurs though? I mean, the low-level stuff.

Stackoverflowing!


Solution

  • You're calling TotalCount from within TotalCount, don't do that.

    You can have another field for the value of the property instead.

    Though, I suspect your code should read as:

    public int TotalCount { get { return UnassignedCount + AssignedCount ; } }
    

    EDIT: as for why the stackoverflow occurs, it is because when you're using Properties, the .NET compiler will actually generate 2 functions, set_PropertyName and get_PropertyName. So in essense, it causes a stackoverflow from the get_PropertyName method call that becomes infinitely deep.