Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

My problem is about the copy of object without reference.

What I have tried:

I try to copy a list of object like this :
C#
List<MyObject> myNewList = new List<MyObject>(myOldList);


The problem is that my new list reference the older list.

Here is my object "MyObject" :

C#
/// <summary>
    /// Model to represent a trip.
    /// </summary>
    [Serializable]
    public class TripModel : BaseModel, IEquatable<TripModel>, IComparableModel
    {
        /// <summary>
        /// Initialises a new instance of the <see cref="TripModel" /> class.
        /// </summary>
        public TripModel()
        {
            this.PropertyBags = new SimpleSerializableDictionary<string, string>();
            this.TripPlans = new SimpleSerializableDictionary<TripEnums.TripPlanType, TripPlanModel>();
            this.PreviewMode = GeneralEnums.PreviewMode.Unchanged;
        }

        /// <summary>
        /// Gets or sets the direction of the trip.
        /// </summary>
        public TripEnums.TripDirection Direction
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the instantiation mode of the trip.
        /// </summary>
        public TripEnums.TripInstantiationMode InstantiationMode
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the number of the next trip.
        /// </summary>
        public int NextTripNumber
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the number of the previous trip.
        /// </summary>
        public int PreviousTripNumber
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the property bags of the trip.
        /// </summary>
        public SimpleSerializableDictionary<string, string> PropertyBags
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the service ID of the trip.
        /// </summary>
        public string ServiceId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the state of the trip.
        /// </summary>
        public TripEnums.TripState State
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the ID of the trip.
        /// </summary>
        public string TripId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the number of the trip.
        /// </summary>
        public int TripNumber
        {
            get;
            set;
        }

        public GeneralEnums.PreviewMode PreviewMode
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the trip plans of the trip.
        /// </summary>
        public SimpleSerializableDictionary<TripEnums.TripPlanType, TripPlanModel> TripPlans
        {
            get;
            set;
        }

        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>Returns true if the two objects are equal false otherwise.</returns>
        public bool Equals(TripModel other)
        {
            if (other == null)
            {
                return false;
            }

            return this.TripNumber == other.TripNumber
                   && this.ServiceId == other.ServiceId
                   && this.TripId == other.TripId
                   && this.Direction == other.Direction
                   && this.State == other.State
                   && this.InstantiationMode == other.InstantiationMode
                   && this.PreviousTripNumber == other.PreviousTripNumber
                   && this.NextTripNumber == other.NextTripNumber
                   && object.Equals(this.PropertyBags, other.PropertyBags)
                   && object.Equals(this.TripPlans, other.TripPlans);
        }

        /// <summary>
        /// Determines whether the specified System.Object is equal to the current System.Object.
        /// </summary>
        /// <param name="obj">The System.Object to compare with the current System.Object.</param>
        /// <returns>Returns true if the two objects are equal false otherwise.</returns>
        public override bool Equals(object obj)
        {
            return obj != null && this.Equals(obj as TripModel);
        }

        /// <summary>
        /// Serves as a hash function for <see cref="TripModel" />.
        /// </summary>
        /// <returns>A hash code for the current <see cref="TripModel" />.</returns>
        public override int GetHashCode()
        {
            return
                new
                {
                    this.TripNumber,
                    this.ServiceId,
                    this.TripId,
                    this.Direction,
                    this.State,
                    this.InstantiationMode,
                    this.PreviousTripNumber,
                    this.NextTripNumber,
                    this.PropertyBags,
                    this.TripPlans
                }.GetHashCode();
        }

        /// <summary>
        /// Adds an information to the object indicating 
        /// if the object has been updated, deleted, inserted
        /// or unchanged.
        /// </summary>
        /// <param name="previewMode"></param>
        public void AddModification(GeneralEnums.PreviewMode previewMode)
        {
            this.PreviewMode = previewMode;
        }


    }



Thank you for your help...
Posted
Updated 11-Feb-22 20:41pm
Comments
BillWoodruff 11-Apr-18 14:30pm    
Looking at your code: why are you using PropertyBags when what you are working with are really simple POCO classes ?

You probably want to clone your original list instead

How do I clone a generic list in C#? - Stack Overflow[^]
 
Share this answer
 
Comments
yaluobth 11-Apr-18 11:27am    
It works... Thank you very much
You could create a copy constructor in your object that accepts an object of the same type:

public MyObject(MyObject obj)
{
    this.Property1 = obj.Property1;
    this.Property2 = obj.Property2;
    ...
}


And then do this when you want to copy it:

List<MyObject> list2 = list1.ConvertAll(x => new MyObject(x));


OR inherit ICloneable, and

C#
public class MyObject : ICloneable<MyObject>
{
    public MyObject Clone()
    {
        return new MyObject{ /* set properties */ };
    }
}


And do this:

List<MyObject> list2 = list1.ConvertAll(x => x.Clone());


OR

You could serialize the existing objects into a stream and deserialize them back into a new list of objects.
 
Share this answer
 
Comments
Maciej Los 11-Apr-18 11:08am    
5ed!
yaluobth 11-Apr-18 11:27am    
It works... Thank you very much
Make it a structure instead of a class or Create a clone method within your class and Return this.MemeberwiseClone;
 
Share this answer
 
Comments
Richard Deeming 14-Feb-22 11:09am    
A structure wouldn't be able to inherit from the BaseModel class. And the copy constructor was already suggested four years ago in solution 2.

If you're going to post a new answer to such an old question, make sure you're adding something new to the discussion.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900