I have a SortedDictionary defined as:
public SortedDictionary<DateTime,RosterLine> RosterLines = new SortedDictionary<DateTime,RosterLine>();
RosterLine itself is a simple struct:
struct RosterLine {
public string RosCd;
public string ActCd;
public double Hrs;
}
I can .Add(dt, rosterLine) no problems, and iterate through the dictionary fine too.
My problem is trying to update the RosterLine values given a specified date eg.
DateTime currDt = new DateTime(2013,12,02);
RosterLines[currDt].ActCd = "SO"; // error here
It tells me: Cannot modify the return value (dictionary def here) because it is not a variable. My goal is to do this with an iterating loop (which I thought might be the problem), but it won't work outside the loop on its own either (as above).
My question is: how do I update a SortedDictionary with a given key (date)?
The reason for the error message is that RosterLine is a struct and by that a value type. The error I get in ideone is:
Cannot modify a value type return value of `System.Collections.Generic.SortedDictionary.this[System.DateTime]'. Consider storing the value in a temporary variable
For value types, the dictionary stores a copy of the value and not a reference to the object on the heap. Also, when retrieving the value (as in dict[DateTime.Today]
), it is copied again. Therefore, changing a property in the way you do in your sample only works on the copy of the value type. The compiler prevents misunderstandings by the error message - if it wouldn't one would wonder why the value in the dict has not been changed.
var dict = new SortedDictionary<DateTime, RosterLine>();
dict.Add(DateTime.Today, new RosterLine());
// Does not work as RosterLine is a value type
dict[DateTime.Today].ActCd = "SO";
// Works, but means a lot of copying
var temp = dict[DateTime.Today];
temp.ActCd = "SO";
dict[DateTime.Today] = temp;
In order to solve this, you could make RosterLine a class or you can work with temp variables as the error message suggests.