Reputation: 703
This is just a 'out-of-curiosity' question, so I can't provide a real world example based on a current problem, but a little dummy code should suffice. What I'm wondering is if there is a straight-forward (and especially fast) way to map an instance of an object to 'this' (a current instance of the exact same type, with access to private members etc.)
public class MyObject {
public MyObject(MyObject other) {
// of course, won't work
this = other;
}
}
All examples and how-to's I've seen take excessive use of reflection, even building up complete expression trees or using frameworks like Automapper, all with their own limitations when the idea seems 'fairly trivial'. Why isn't it just possible to copy over all pointers/references etc. from one place in memory to another, given that the allocated space etc. is exactly the same?
Upvotes: 1
Views: 63
Reputation: 494
AFAIK, there isn't a straight forward way to do that for the own instance (this). And I imagine that copying the data from the other instance to this would suffice. What might be an alternative for you is work with a static instance, but this has some particularities if you need to work with more then one instance.
public class MyObject {
private static MyObject _instance;
public static MyObject Instance
{
get { return _instance; }
set { _instance = value; }
} }
PS: I wrote this post from my cell, so forgive me if you run into minor errors, as I wasn't able to test it before posting. I will update the post as soon as I'm able to test the code.
Upvotes: 1
Reputation: 37020
If this was possible you´re simply referencing other
by a new reference, but not copy its content to a new instance of MyObject
. So your constructor would simply return a new reference to the already existing instance. What you need is a completely new instance of MyObject
, don´t you? So you have to create one using one of its constructors. If you have a copy-constructor that achieves this you´re fine:
public class MyObject {
public MyObject(MyObject other) {
this.Prop1 = other.Prop1;
}
}
Of course there are some shorter (but not neccesarily saver) appraoches - e.g. using reflection and simply copy all property values from one instance to another one. However basically you still end up creating a completely new instance by setting of of its members appropriately.
The reflection-code may look similar to this:
public class MyObject {
public MyObject(MyObject other) {
var props = typeof(MyObject).GetProperties();
foreach(var p in props)
{
p.SetValue(this, p.GetValue(other));
}
}
}
However this only applies to the public properties, you have to do this with the fields and the private or internal members also.
Upvotes: 1