RieqyNS13
RieqyNS13

Reputation: 495

Dictionary loses values when passed as a parameter

My title question is absolutely the same as this question

However that does not answer my question.

static void Main() {
    Dictionary<string,int> d=new Dictionary<string,int>();
    d["asu"]=1;
    d["babi"]=1;
    c(d);
    Console.Write(d["asu"]);
    //output=0
}
static void c(Dictionary<string,int> d){
    d["asu"]--;
}

The above code decrease a value in d variable inside Main method, when it should only decrease value inside c() method and should not decrease inside Main method too. How do I keep the Dictionary in Main method so the values not decreased by passed parameter.

Upvotes: 1

Views: 653

Answers (2)

Tommy
Tommy

Reputation: 3124

Create a dictionary copy before passing into method c

c(new Dictionary<string, int>(d));

Otherwise, variables point to the same object.

Upvotes: 3

Blorgbeard
Blorgbeard

Reputation: 103525

Dictionary is a reference type. You are not making a copy of the data when you pass it around. You're just passing a reference to the same underlying object.

If you want to modify a copy, you'll need to explicitly make one; try:

var copy = d.ToDictionary(t=>t.Key, t=>t.Value);

Upvotes: 5

Related Questions