Click here to Skip to main content
15,907,910 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am trying to figure out how to share the same object among 2 other objects.
So let's call it class A and B for simplicity sake.

Class B has a copy of class A in it.

Creating object X and Y from class B and creating object Z from class A.

I want both object X and Y to have the same reference to object Z and when either objects modify Z, both of them have the updated copy.

I know this can be simplified if I were to use a static variable but that applies to all objects of the class. I just want the variable to be shared among some of the objects rather than the whole series.

Thanks in advance.
Posted
Comments
Sergey Alexandrovich Kryukov 23-Jan-13 20:55pm    
I answered, but you should be more ready to asking question, read literature very thoroughly...
—SA

1 solution

You are lost very well, need to go from the very beginning.

Class is a type. You cannot copy a type. You can copy an object, instance of a type. Classes are reference types. When you create, say, an instance of a type, your get too references of the same objects.
C#
class A { /* ... */ }

A a = new A();
A b = a;
// at this point, a and b are different references to the same object

The reference itself is also an object, so an object of a reference type is a reference itself, which can be considered as a an object, and the object referenced by a reference. This way, a.SomeMember = 3 will make b.SameMember also 3. At the same time, if later you write b = new A();, you will loose an extra reference to the same object as the one referenced by a and have two different objects, referenced by two references. In other words, new assignment to the reference b will not affect a.

Now, imagine that two different objects have fields of the type A. When you copy one to another, they will reference the same object. This object will be shared between two instanced of this other class or structure. Or they can reference distinct, different object of A.

This is all the very, very basics which you should understand 100% clearly. Without it, there is no .NET programming at all. And this is the point where you did not start "read" OOP yet…

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900