mehdi_mousavi said:
Hi folks,
Consider the following line of code:
Address addr = ei.Address;
where ei is an instance of a class that has got a property of Address
type.
The question is that what is happening in the above assignment? Unlike
the C/C++, it seems that the above code instructs the compiler to point
the addr variable to the same location where ei.Address already
resides, i.e, it's somehow a pointer to the ei.Address.
You say "unlike C/C++", but this is not necessarily so. In C, if the
Address field of ei is a pointer, then in fact addr will contain the
same pointer and any modifications to addr->Blah will also change
ei.Address->Blah.
Others here have given good answers, but I wanted to adapt them to your
situation. What will happen in this situation depends upon two things:
1) Whether the type Address is a class or a struct.
2) Whether the Address member of ei is a field, a property that returns
a reference that is part of the state of ei, or a property that returns
a clone of the Address held by ei.
Most here have talked about point #1. Specifically, if the Address type
is a struct--that is, a value type--then assignment and/or returning an
Address from a method implies copying it.
public struct Address
{ ... }
So, if this were the case then changes to the Address held by addr
would not affect the Address held by ei. This is regardless of point #2
above.
If the Address type is a class, then point #2 comes into play: is
ei.Address a field, or is a property. If it's a property, does it
return a reference held by ei or return a clone?
If the Address type is a class and ei.Address is a field:
public class Address
{ ... }
public class EiType
{
public Address Address;
}
then yes, addr will refer to the same object instance as does
ei.Address, and changes to one will be visible when referring to that
same object via the other reference. In effect the "two" will appear to
change in synch, because in reality there's only one.
Similarly, if the field is wrapped in a property that just returns the
object reference, the same applies:
public class Address
{ ... }
public class EiType
{
private Address _address;
public Address Address { get { return this._address; } }
}
However, if ei.Address is a property that returns a clone:
public class Address : ICloneable
{
public override object Clone() { ... }
}
public class EiType
{
private Address _address;
public Address Address { get { return
(Address)this._address.Clone(); } }
}
then the reference assigned to addr will be to a different object
instance than the one held by ei._address, and changes to one will not
be reflected in the other.