0

So I'm creating a programme right now and I'm only needing to create one object of a specific class/subclass. However I want to be able to edit this object within several different button 'events'. I'm looking to probably create the object within the main function as soon as the program starts, but then be able to use the object out of the scope of 'main', such as when a button is pressed. I've looked around and I can't seem to find any particular way that this would work. I'm writing it in c# with Windows Forms.

So any suggestions would be helpful, thanks!

1 Answers1

0

What you are looking for is the Singleton Pattern.

It works by exposing a static property on your class that will return always the same instance of it:

public sealed class MySingleInstanceClass
{
    private static readonly MySingleInstanceClass instance = new MySingleInstanceClass();

    public static MySingleInstanceClass Instance 
    { 
        get
        {
            return instance;
        }
    }

    static MySingleInstanceClass()
    {
    }

    // Use a private constructor so no one besides your own class can create an instance of it
    private MySingleInstanceClass()
    {
    }

    public string SomeProperty { get; set; }
}

So now, whenever (and wherever) you need to access this class, you'd use it like that:

MySingleInstanceClass.Instance.SomeProperty = "foo";
Bernhard Koenig
  • 1,252
  • 15
  • 23
  • Class should ne `sealed`so it cannot be inherited from – NineBerry Oct 09 '16 at 14:44
  • I had read some on Singleton Patterns, however the class I'm building has a subclass inheriting from it, as well as me looking to change the details of the class itself. From what I've read I can't do these with a singleton class, or have I just misread somewhere? – D. Jamieson Oct 09 '16 at 15:17
  • @D.Jamieson In this case I'd really need a more detailed description of what exactly you want to achieve. A Singleton is the most clean solution when you only ever need one instance of your class in your application. If you need inheritance, that does not seem to be the case. But it might also be ok to just have one (not singleton-controlled) instance assigned to some static property on some static class if it makes sense. A way to achieve a singleton could also be to use a dependency injection container that handles the lifetime of your object. This would also allow inheritance. – Bernhard Koenig Oct 09 '16 at 16:41
  • @NineBerry Normally I follow a never seal a class approach, but in this case I agree that it makes enough sense to prevent unintended behavior. I added it. – Bernhard Koenig Oct 09 '16 at 16:45