Class Instances

IanBr

Member
Joined
Jul 3, 2021
Messages
6
Programming Experience
10+
I have a "best practice" question. In a program I have 3 classes A, B & C. There can only be a single instance of class A but methods in that instance must be useable from both B and C.
Staying within the 'confines' of OOP, how and where do I declare the instance of A?
If there's a better way of doing this I'd welcome hearing it.
 
Last edited:
Unlike other languages where declaration is automatically instantiation, in C# most object require that you call new to create an instance. So re-read the tutorial see where and when that new happens.
 
Unlike other languages where declaration is automatically instantiation, in C# most object require that you call new to create an instance. So re-read the tutorial see where and when that new happens.
Well I looked more carefully at the example and I did miss the NEW, but to me it creates more questions than answers. Here's the code:
C#:
public sealed class Singleton1 {
    private Singleton1() {}
    private static Singleton1 instance = null;
    public static Singleton1 Instance {
        get {
            if (instance == null) {
                instance = new Singleton1();
            }
            return instance;
        }
    }
}
That's the entire thing. I don't know anything about Singleton's and this code makes no sense to me, the NEW for the class appears to be in the class definition itself which is impossible. I think I need to find out more about these things, for a start I have no idea exactly where in the program this code should be inserted. If anyone has an example of that I'd be very interested to see it but I should be able to find better/more complete examples elsewhere.

HOWEVER:
Going back to my original question. Where exactly would I place a class instantiation which could be accessed from within other classes? I don't understand how oop prefers this to be done. It seems impractical to pass a reference to the class instance into every other class that needs it (there may easily be hundreds of them) and yet public class instances and referencing them from within a class seems to break encapsulation.
 
Last edited:
It is exposed as a static property, you get it from the class: A.Instance
 
The point of the Singleton pattern is that the type provides the one and only instance. The constructor is private so that it can only be accessed inside the type. The only way to get an instance is via the Instance property. When you get that property, it first checks whether an instance already exists and, if not, creates one. That one instance is then returned. No matter how many times you get that property, it will always return that one and only instance. Any time and anywhere you want that object, get it from that property.
 
Back
Top Bottom