toddhd

Please consider the following (oversimplified class). What I want to do is pass this class another instance of Person, and have it assign its own properties to match those of the class I'm passing in.

public class Person
{
private string firstName = string.Empty;
private string lastName = string.Empty;

public
string FirstName
{
get{return firstName;}
set{if (firstName == value) return;
firstName =
value;}
}

public string LastName
{
get{return lastName;}
set{if (lastName == value) return;
lastName =
value;}
}

public void Load(Person p)
{
this = p;
}
}

The problem is in the Load() function - you can't do "this = p;". Instead you have to:
this.firstName = p.firstName;
this.lastName = p.lastName;

In this simple example, that's not such a big deal, but in my real-world case, my class has hundreds of properties, and should I add/delete/change any of those, then I would need to also go back and make sure I properly changed the Load() function to match those changes.

So my question is - is there an equivilent way to do something like this=p without having to resort to spelling out each and every property individually. I hope I explained this properly, if you don't understand, please ask.




Re: Visual C# General Classes 101: How to load a class with a copy of the same class?

Galin Iliev

you can use reflection to get all properties' values and assign them to current instance (again with reflection)

I use this approach to achieve different goal but you can use part of the code from this article Discard changes in business objects

hope this helps






Re: Visual C# General Classes 101: How to load a class with a copy of the same class?

Friendly Dog

If you are lucky you can use MemberwiseClone to creat a shallow copy. By "lucky" i meant if the class only contains value types. If it contains a reference type, the referenece is copied instead of referred object.

Or, you'll need to implement ICloneable on the class that is to be copied - it may be easier than you've thought. First, the interface only contains one Clone() method, and you can use MemberwiseClone first, then fix up the reference types.