Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assignment overloading and immutable types

Status
Not open for further replies.

MuadDubby

Programmer
Sep 23, 1999
236
CA
Hi

I'm trying to create a class that will support a deep copy when using the assignment operator, much like how the string class does it.

Normally speaking, the assignment operator will create a reference copy of the object, which means that both the original and new object point to the same data. I'm trying to emulate what the string class does, which is that the two objects point to different sets of data after the assignment. I know we have the ICloneable interface, but I'd like to avoid using it. Any ideas? There has to be a way. If string can do it, so can we ...

My ideal scenario would be:
Code:
Employee employee1 = new Employee("Joe");
Employee employee2 = employee1;
employee1.Name = "Jane";

// At this point, both employee1.Name and employee2.Name = "Jane". I want this to be employee1.Name = "Jane" and employee2.Name = "Joe".
 
Addendum

I've considered using immutable types (simple example: but the problem with those is that in my case I need to be able to set properties on the object without re-instantiating it every time. But if I change the property, it automatically affects the other references to the same object.

Thx.

Muaddubbby
 
you could make one of the constructors in the Employee class take an Employee object? This would not be immutable though. do you want the old Employee object to be garbaged at this point? It will do what you want though.

Code:
public Employee(Employee employeeToClone)
{
   // create an exact copy of Employee here
   FieldInfo[] fields =
      typeof(Employee).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
   foreach (FieldInfo f in fields)
   {
      f.SetValue(this, f.GetValue(employeeToClone));
   }
}

To use this constructor you can now just
Code:
Employee employee1 = new Employee("Joe");
Employee employee2 = new Employee(employee1);
employee1.Name = "Jane";

Hope this helps?

Age is a consequence of experience
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top