Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Let multiple class share the same instance of another class

Tags:

c#

class

instance

Is there any way to let multiple class share the same instance of another class? So in my c# program i've got three class Gamelogic(A), FPSController(B), and SpawnPlayer(C).

In my case class B and C would use and alter some variables in A, in order to use the variables i'm currently instantiating A in two different classes and then use dot notation to access the variable from the instance of A, but the problem is that after A instantiated in different classes, the change in instance.variable does not share between B and C class at all.

Would static type be a good way of solving this? Or writing a main would be better.

Any suggestions would be appreciated.

like image 467
libra Avatar asked Feb 07 '23 09:02

libra


1 Answers

There are a few ways. Here is one:

One way would be dependency injection. You can pass the instance of A along to the constructors of B and C (or to a setter/property of B and C):

A a = new A();
B b = new B(a);
C c = new C(a);

But this doesn't allow you to change the A reference in both objects easily, which seems to be your problem. One way to easily change the reference, is to wrap the reference in another object somehow.

A nice way to do this could be to create a Context object and pass that context object along to B and C instead of passing A. The context object plays the role as our wrapper. A context object becomes more useful if multiple variables needs to be shared between them (the shared/global state) - see the "Context pattern". Example:

public class Context {
    public A a;
    public ...other state you want to share...;

    public Context(A a) { this.a = a; ... }
}

...

A a = new A();

Context context = new Context(a,...);

B b = new B(context);
C c = new C(context);

Depending on your situation, a static variable might be fine, however. (Or a singleton)

(In some cases passing the A-instance along to the methods of B and C, rather than to their constructor, might be better - then they also always get the current version of a (and might be more thread-safe))

like image 95
DisplayName Avatar answered Feb 16 '23 03:02

DisplayName