• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 750
  • Last Modified:

C# Copy Properties from one Object to Another.

Hi Experts,
i have a class as below
public class Employee
{
public int ID{get;set;}
public string Name{get;set;}
}
Employee emp = new employeee{id =1 NAme = 'aaa'}

Employee  emp1 = emp;
emp1.name = "BBB";

I do not want  emp's name property also to be changed to "BBB";

How can i achieve this ,  Using reflection do i need to copy properties from one object to other or is there a better way , please advice.
0
B_Pati
Asked:
B_Pati
1 Solution
 
käµfm³d 👽Commented:
Here's your problem:  you haven't created two objects. You've created one object with two references pointing to it. Even reflection wouldn't help you here.

My suggestion would be to create a "copy" constructor that can initialize the object accordingly. For example:

public Employee(Employee template)
{
    this.ID = template.ID;
    this.Name = "N/A";
}

Open in new window


Then you could do:

Employee emp = new Employeee{id =1 NAme = 'aaa'}

Employee  emp1 = new Employee(emp);
emp1.name = "BBB";

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
The copying of all the values to the new instance can be accomplished with Reflection, but I don't know that it's worth it unless you have a ~huge~ number of properties that you don't want to list out manually.  The number of lines of code will probably end up being around the same, except that you have to use a bunch of brain power use the Reflection approach and then you need to worry about bugs...
0
 
B_PatiAuthor Commented:
Thanks kaufmed: This help me with out writing reflection code.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now