I am working on porting a VB6 application to C# (Winforms 3.5) and while doing so I’m trying to break up the functionality into various classes (ie database class, data validation class, string manipulation class).
Right now when I attempt to run the program in Debug mode the program pauses and then crashes with a StackOverFlowException. VS 2008 suggests a infinite recursion cause.
I have been trying to trace what might be causing this recursion and right now my only hypothesis is that class initializations (which I do in the header(?) of each class).
My thought is this:
- mainForm initializes classA
- classA initializes classB
- classB initializes classA
- ….
Does this make sense or should I be looking elsewhere?
UPDATE1 (a code sample):
mainForm
namespace john
{
public partial class frmLogin : Form
{
stringCustom sc = new sc();
stringCustom
namespace john
{
class stringCustom
{
retrieveValues rv = new retrieveValues();
retrieveValues
namespace john
{
class retrieveValues
{
stringCustom sc = new stringCustom();
9 times out of 10, infinite recursion bugs are caused by bad property accessors:
I’ve also had it happen when doing major refactorings with method overloads; sometimes you accidentally end up with a method calling itself when it’s supposed to call a different overloaded method.
Either way, you should be able to tell by looking at the call stack for the exception and checking for a repeating pattern. If you see one, then your problem is somewhere in that loop.
Edit – well, based on your example code, you definitely have infinite recursion in the initializers. I have no idea what that code is supposed to be doing, but it’s never going to terminate.
StringCustomimmediately createsRetrieveValueswhich immediately creates anotherStringCustom, and so on.This is one reason why circular class dependencies are typically considered a code smell. Whenever you see
ClassAdepending onClassBandClassBdepending onClassAthen you should try to refactor; the exception is ifClassBis entirely owned and managed byClassA(i.e. an inner class), which is clearly not the case here. You need to eliminate one of the dependencies somehow.