1

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)?

Pete855217
  • 1,570
  • 5
  • 23
  • 35
  • Thanks L.B! That did the trick. I'm wondering why though? When I tested a new SortedDictionary that had as its value a simple string, it worked too, so I'm figuring it's something to do with the struct or the way I access it. If you make your comment an answer I'll make it the answer. Thanks again. – Pete855217 Dec 02 '13 at 07:49

1 Answers1

2

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.

Markus
  • 20,838
  • 4
  • 31
  • 55
  • Thanks Markus, that explains the situation well. Using the struct, I'm accessing copied values, not the reference to the object itself. I guess making it a class forces me to use the object itself (it's made via a new statement with its inherent pointer). Is that right? – Pete855217 Dec 02 '13 at 09:23
  • @Pete855217: yes, that's right. When using a reference type (a class), the reference is stored and handed out and you work on the object on the heap itself. – Markus Dec 02 '13 at 09:26