I was just wondering what is considered the best practice when assigning reference type properties, and under no circumstances do I want them to share instance of the object (I want a deep copy).
Let's say I have a class:
public class GeoLocation : SomeBase, ICloneable // Only contains value type properties
{
public double AValueTypeProperty { get; set; }
public GeoLocation Clone()
{
return new GeoLocation{ AValueTypeProperty = this.AValueTypeProperty };
}
object ICloneable.Clone()
{
return Clone();
}
}
This class is used as a property by several other classes:
public class PointOfInterest
{
public GeoLocation Location { get; set; }
// Other members
}
public class SomeOtherTypeOfPoint
{
public GeoLocation Location { get; set; }
// Other members
}
What I want to avoid is for people to write a function that makes these classes share a GeoLocation instance, when they only want to copy it. As work will be done on those point classes independently and we don't want them to affect eachother.
If I want to assign the Location value (and only that value) from one of them to the other as a new copy of GeoLocation, one way to do it is to clone.
Let's say a developer needs to write this gibberish function to move a point to the same location as another point, but not have them affect each others location by later processing.
public void MovePointOfInterestToSomeOtherTypeOfPoint(PointOfInterest poi, SomeOtherTypeOfPoint other)
{
poi.Location = other.Location.Clone();
}
The above seems a bit error prone in my case as we always want a copy, and if someone forgets to write ".Clone()" here it can cause some unfortunate side effects.
Or is it normal to clone in the setter for Pop in both classes? As in:
public class PointOfInterest
{
private GeoLocation _loc = null;
public GeoLocation Location { get => _loc; set => _loc = value.Clone(); }
// Other members
}
Which I'm not terribly fond of, as it seems I need a private field for this to work, but at least it seems safer than hoping developers don't forget to clone.
Alternatively, in C++ I'm used to be able to create classes on the stack and treated similarly to what is called value types in C#, is there any way to achieve the same in C#. I wish to use inheritance, so structs aren't exactly what I'm looking for.
Thanks in advance.