muhayyuddin gillani
muhayyuddin gillani

Reputation: 71

How to copy values of a class to other without changing their memory locations

I would like to know if is there any way to copy one object to the other, without changing their memory locations, in example below.

 class PersonData
    {
        public string PersonName;
        public int age;

        public PersonData(string name, int age)
        {
            this.age = age;
            PersonName = name;
        }
    }
    class Program
    {

        static void Main(string[] args)
        {
            object person1 = new PersonData("FirstPerson",20);
            object person2 = new PersonData("secondPerson",30);

            person1 = person2;
        }
    }

person1 will start pointing to the memory location of person2. what I would like to do just copy the VALUES of person2 at the memory location of person1. is there any method other than

person1.age = person2.age;
person1.name = person2.name;

because I don't know the fields of the object beforehand.

thank you in advance.

Upvotes: 0

Views: 798

Answers (2)

Vic
Vic

Reputation: 950

Use deep copy,

Deep copy will create a instance and it copy value to own memory location.

.Net have a many way to do this.

I think use serialize object is the most easy way.

Sample code (Use Newtonsoft.Json package):

 class PersonData
    {
        public string PersonName;
        public int age;

        public PersonData(string name, int age)
        {
            this.age = age;
            PersonName = name;
        }
    }
    class Program
    {

        static void Main(string[] args)
        {
            object person1 = new PersonData("FirstPerson",20);
            object person2 = new PersonData("secondPerson",30);

            //First ,serialize the object, then copy to other object with deserialize
            person2 = JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(source));
        }
    }

Upvotes: 1

Aaron G
Aaron G

Reputation: 83

All objects have a protected function called MemberwiseClone that does a shallow copy of the members of a class. Typically this is exposed via implementing the ICloneable interface. However, ensure you understand what shallow copy means. For value-type member variables it copies the values. For reference-type member variables it copies the reference.

public class PersonData : ICloneable {
    public string PersonName;
    public int age;

    public PersonData(string name, int age)
    {
        this.age = age;
        PersonName = name;
    }

    public object Clone() => this.MemberwiseClone();
}

class Program
{

    static void Main(string[] args)
    {
        object person1 = new PersonData("FirstPerson",20);
        object person2 = new PersonData("secondPerson",30);

        person1 = person2.Clone();
    }
}

Upvotes: 1

Related Questions