0

I have Struct

    struct User
    {
        public int id;
        public Dictionary<int, double> neg;         
    }
    List<User> TempUsers=new List<users>();
    List<User> users = new List<User>();

my Problem is, when I run this code

TempUsers=users.ToList();
TempUsers[1].neg.Remove(16);

neg dictionary in users aslo remove key with value=16

Afshin
  • 4,197
  • 3
  • 25
  • 34

2 Answers2

5

That is because the Dictionary is a reference type. You should clone it, for sample:

class User : IClonable
{
    public int Id { get; set; }
    public Dictionary<int, double> Neg { get; set; }

    public object Clone()
    {
        // define a new instance
        var user = new User();

        // copy the properties..
        user.Id = this.Id;    
        user.Neg = this.Neg.ToDictionary(k => k.Key,
                                         v => v.Value);

        return user;
    }
}

You shouldn't use a struct in a type like this. In this link, there is a good explanation about when and how you should use a struct.

Community
  • 1
  • 1
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
2

Dictionary is a reference type. You should clone you dictionary: this is an example:

    struct User : ICloneable
{
    public int id;
    public Dictionary<int, double> neg;

    public object Clone()
    {
        var user = new User { neg = new Dictionary<int, double>(neg), id = id };
        return user;
    }
}