Afshin
Afshin

Reputation: 4215

Define Dictionary in struct with C#

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

Upvotes: 0

Views: 5163

Answers (2)

user1968030
user1968030

Reputation:

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;
    }
}

Upvotes: 2

Felipe Oriani
Felipe Oriani

Reputation: 38598

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.

Upvotes: 5

Related Questions