0

Hi i am trying to clone a object which has a member list object

 public class GrossTemplatesInfo
{
    public List<GrossTemplates> grossTemplates { get; set; }
    public object Clone()
    {
        GrossTemplatesInfo other = (GrossTemplatesInfo)this.MemberwiseClone();
        other.grossTemplates = new List<GrossTemplates>(grossTemplates);
        return other;
    }
}
public class GrossTemplates : ICloneable
{
    public string tempID { get; set; }
    public string PreferenceName { get; set; }
    public string PreferenceValue { get; set; }
    public bool isDefault { get; set; } 
    object ICloneable.Clone()
    {
        return this.Clone();
    }
    public object Clone()
    {
        return this.MemberwiseClone();
    }

}

and my method is something like this

public static GrossTemplatesInfo LoadInitialdata(string caseType)
    {
        GrossTemplatesInfo a = new GrossTemplatesInfo();
       GrossTemplatesInfo b = a.Clone() as GrossTemplatesInfo; 
    }

I have done this and i am not getting the values in cloned object 'b' that are in original object 'a'. any help? i am kinda new to this cloning mechanism.

Sheiky
  • 41
  • 1
  • 7
  • i need to clone GrossTemplatesInfo object in above code , how can i acheive it. – Sheiky Jul 09 '14 at 05:47
  • 2
    possible duplicate of [Deep cloning objects](http://stackoverflow.com/questions/78536/deep-cloning-objects) – Uriil Jul 09 '14 at 05:48
  • updated my code , do i need to do member wise clone in class GrossTemplatesInfo too? – Sheiky Jul 09 '14 at 05:54
  • It's hard to tell without knowing context what do you need – Uriil Jul 09 '14 at 05:57
  • I need to clone the GrossTemplatesInfo object – Sheiky Jul 09 '14 at 06:07
  • what is going wrong in the above code? the cloned object 'b' is not showing the values that are in a. – Sheiky Jul 09 '14 at 06:31
  • @Sheiky you are creating a list with original values in it. You need to copy the inner content too: `other.grossTemplates = new List(grossTemplates.Select(i => (GrossTemplates)i.Clone());` – Askolein Jul 09 '14 at 06:38

1 Answers1

0

You want to clone your container class, so you need to implement ICloneable on it too (GrossTemplatesInfo).

Dealing with the GrossTemplates class, three possibilities:

1, Do it manually:

public object Clone()
{
    return new GrossTemplates()
    {
        tempId = this.tempId,
        PreferenceName = this.PreferenceName,
        PreferenceValue = this.PreferenceValue,
        IsDefault = this.IsDefault
    };
}

2, Use a generic helper as describe here (cf @Uriil comment)

3, Rethink the whole context (or explain it to us) and do not copy instances

If applicable, 3 is the way to go.

Community
  • 1
  • 1
Askolein
  • 3,250
  • 3
  • 28
  • 40