sYsTeM
sYsTeM

Reputation: 37

Can not modify return value Dictionary <string, Point> because it is not a variable

I'm getting this error in the title, and here is the problem code:

Dictionary<string, Point> dicPoint = new Dictionary<string, Point>();
dicPoint.Add("point1", new Point());
dicPoint["point1"].X++;

At the time of incrementing X, it gives error. What is the solution to this problem?

Upvotes: 3

Views: 399

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503090

I assume that the Point type you're using is a struct. Therefore fetching dicPoint["point1"] will create a copy of the value. Changing that would not change what's in the dictionary. Instead, you'll need to fetch the value, modify it, then replace the entry in the dictionary:

var point = dicPoint["point1"];
point.X++;
dicPoint["point1"] = point;

Upvotes: 5

Related Questions