Jonas Lindahl
Jonas Lindahl

Reputation: 802

Best way to inherit class with data?

Not sure how noob or advanced this question is, but I've been having kind of trouble finding a good answer so thought I give it a try here.

To describe my question in words is the following. I have a program that Init's a "engine" at startup that is the source for all data and information for this program. The thing is right now if I write a new class right now I have to include it when the class is created.

public class ClassName(TMEngine engine)
{
......
}

What I wonder is if how I could use a "child : parent" class relation to have this on the parent so the only this I have to know is what its called. I have written classes both for the Form and UserControl to have some extras in them so there is a parent class.

public partial class msgCtrlContainerCtrl : TMUserControl
{
     public msgCtrlContainerCtrl(TMEngine engine)
     {
        ......
     }
}

As this is a WinForms application I init the engine in the form, but would like all controls created in it used the same engine.

Setting up the engine on "Load-event" in the TMUserControl does not work right now as the UserControl will be initialized on "add" as a UserControl, and the Load event will be run much further behind this.

And you can not look for a parent to the control as the parent-relation has not been initialized yet when you do the "add" for a new control.

So any ideas how to solve this in the best way to place this engine in sync in my extended UserControl class I call TMUserControl here or dose it have to be in every class that uses it?

Upvotes: 1

Views: 125

Answers (1)

BeemerGuy
BeemerGuy

Reputation: 8269

Are you looking for something like this?

public class TMEngine
{
   private TMEngine() {}

   private static TMEngine instance;    
   public static TMEngine Instance
   {
      get 
      {
         if (instance == null)             
            instance = new TMEngine();             
         return instance;
      }
   }

   public string GetSomeStringData()
   {
       ...
   }
}

This will be your engine... so you can go ahead and construct the way you want.
Now you need an abstract for all your classes that will use the engine.

public abstract class EnginedClass
{
    public static TMEngine Engine { get { return TMEngine.Instance; } };
}

Then just implement your classes using it:

public MyNewClass : EnginedClass
{
    ...
    public string GetSomeData()
    {
        ...
        return Engine.GetSomeStringData();
    }
    ...
}

Upvotes: 1

Related Questions