I'm working on doing some refactoring of functions in an existing ASP.NET MVC application, and came across the following small recursive function within a controller. I'm a little new still to C# & .NET, so please bear with me if I get some things wrong.
private int _bl;
[Session]
public void TotalMaterialSubCategories(IEnumerable<Category> materialMasterCats, int i)
{
foreach (var materialMasterCat in materialMasterCats)
{
_bl = _bl + 1;
materialMasterCat.Level = i;
if (materialMasterCat.ChildCategories.Count != 0)
{
TotalMaterialSubCategories(materialMasterCat.ChildCategories.ToList(), i + 1);
if (materialMasterCat.Parent == 0)
{
materialMasterCat.SortOrder = _bl;
_bl = 0;
}
}
}
}
The thing about it that concerned me is this private int _bl
statement. Within this class, the only references to this variable are associated with this function.
I thought the line _b1 = _b1 + 1
might not be reliable because it's not manually initialized. Looking into it though, I believe that since it's an int
, it cannot be null or left 'uninitialized', so it's getting a default value of 0; corroborated by the MS Docs. The way the recursion looks like it bubbles up makes me think it'll be set back to 0 at the end of this function call as well. Finally, I'm pretty sure each independent web request gets a separate instance of this controller, so it seems like the way this is written, it should function as expected.
However, I just sort of wondered why this would be written like this. Is there a reason that this isn't just a local variable to the function, initialized with 0? Can you rely on local private variables across functions in controllers? Also, are any of my assumptions / determinations incorrect?