0

I have one class

class MatchAddress
{
    public string Name { get; set; }
    public string Taluka { get; set; }
    public string District { get; set; }
    public string Pincode { get; set; }
    public float Rank { get; set; }
}

I have create new list using this class as mentioned below

var dst = ds.Tables[0].AsEnumerable()
                      .Select(s => new MatchAddress 
                       { 
                           Name = s.Field<String>("officename").Trim().ToLower(), 
                           Pincode = Convert.ToString(s.Field<double>("pincode")).Trim(), 
                           Taluka = s.Field<String>("Taluk").Trim(),
                           District = s.Field<String>("Districtname").Trim(), 
                           Rank = 0f 
                       })
                      .ToList();

I have also initialize new list List<MatchAddress> lm;

Now I'm assign dst list to lm like below

lm = dst ;


foreach (MatchAddress ma in lm)
{                       
    if (ma.Name == "xyz")
    {                              
        ma.Pincode = null;
    }
}

after this sure the Property Pincode for the list lm set to null where name = "XYZ".

and for that reason list lm are update and set pincode field null .

but my question are that why that list lm also update the result of list dst.

and lm list also set pincode null in the list dst.

and we make the clone of the dst list into lm so why list lm change the also list dst ??

I know to reason behind this not the answer why this happen if you know then please let me now.

I don't want to the answer of this question

RBT
  • 24,161
  • 21
  • 159
  • 240
KARAN
  • 1,023
  • 1
  • 12
  • 24
  • 1
    You are not making a clone of `dst`, you assign the `dst` List to the `lm` List which is assigned by reference, that is why both lists are changing. – Bojan B Sep 07 '16 at 06:06

2 Answers2

1

List is a reference type data. but you can make clone if you want. here is the simple extension method for that

static class Extensions
    {
        public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
        {
            return listToClone.Select(item => (T)item.Clone()).ToList();
        }
    }
Gayan
  • 2,750
  • 5
  • 47
  • 88
0

Because List is a reference type data. Both lm and dst are pointing to the same data. If you want both lists to be independent, you can do it as:

List<MatchAddress> lm = dst.ConvertAll(address => new MatchAddress(Name = address.Name, Pincode = address.Pincode, Taluka= address.Taluka, District = address.District, Rank = address.Rank));
Richa Garg
  • 1,888
  • 12
  • 23