Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about non-static members of a singleton (C#)

I have a question about singletons that I think I know the answer to...but every time the scenario pops-up I kinda second guess myself a little so I would like to know the concrete answer.

Say I have two classes setup as so...

 public class ClassA
 {
     private static ClassA _classA;

     public static ClassA Instance { get { return _classA ?? LoadClassA(); } }

     private ClassA(){}

     public static ClassA LoadClassA()
     {
         _classA = new ClassA();
         return _classA;
     }

     private ClassB _classB = new ClassB();

     public ClassB ClassB { get { return _classB; } set { _classB = value; } }
 }


 public class ClassB
 {
 }

My question is simple.

I'm wondering if the _classB field is treated as static as well if I access the singleton for ClassA? Even though I didn't declare _classB as a static member.

I've always basically just guessed that _classB it is treated as static (one memory location) but I would like to know for sure. Am I wrong? Is a new object created for _classB every time you access it from singleton ClassA...even though there is only one ClassA in memory? Or is it because I newed up _classB on the declaration that causes there to be only one instance of it?

Thanks in advance, -Matt

like image 320
matt_dev Avatar asked Jul 06 '09 17:07

matt_dev


1 Answers

When you create a singleton, you're creating a single static instance of a non-static type.

In this case, your type (Class A) contains a reference to another type (Class B). The static instance will hold a single reference to a single instance of a Class B object. Technically, it is not "static", but since it's rooted to a static object (the class A instance), it will behave like a static variable. You will always have one and only one Class B object (pointed to by your Class A instance). You will never create more than one Class B instance from within Class A.

There is nothing, however, preventing a second Class B instance to be generated elsewhere - this would be a different instance.

like image 109
Reed Copsey Avatar answered Oct 30 '22 03:10

Reed Copsey