Search code examples
c#.netwinformsclassclass-design

Instantiating each of the two classes in one another


I have a C# class question which I hope to get some help with. I have one class called CountdownUserControl. There are a number of functions within this class. I then have another class called Min. There are certain things I need in this form within CountdownUserControl class so I create an instance of it within CountdownUserControl:

public partial class CountdownUserControl : UserControl
{
    //-----------------------------------------------
    // Private data members
    //-----------------------------------------------
    private Min _Min = new Min();

However within the Min class I also would like to use a function which is contained within the CountdownUserControl class - however I cannot create an instance of it within the Min class such as

public partial class Min : Form
{
    private CountdownUserControl CU = new CountdownUserControl();

so that within Min class I could do CU.Method_I_want();

as this will give a stackoverflow. Does anyone know a solution around this? Thanks for your time.


Solution

  • All these answers are great, but you should also consider the fact that cyclic dependencies are generally really difficult to work with. Your classes should be somewhat isolated units with a single purpose. They should be loosely coupled from each other. If you redesign your classes to eliminate cyclic dependencies and follow these guidelines, you will write better and more maintainable code in general and will have less issues like this in the first place.