Dictionaries and the objects they contain!

I was just wondering, is there some way to synchronize the modification of objects that are in dictionaries (or any other IEnumerable interface for that matter), if they are modified without referring to the dictionary

I find that this code snippet doesnt work (I might be too naive):

foobar bar = new foobar();
bar.setText("hollathere");
Dictionary <string, foobar> someDict = new Dictionary<string, foobar>();
someDict.Add("handle", bar);

Now if I modify bar directly, without going through the dictionary, the changes aren't reflected in the dictionary. Same is the case the other way round.

bar.setText("blahblahblah");

and executing

someDict["handle"].getText();

would return "hollathere" whereas I want it to return "blahblahblah". Ok I know it might sound stupid and you'd think that this kills the whole purpose of the dictionary, but still...

Anyone helping me with it




Answer this question

Dictionaries and the objects they contain!

  • SkyMike99

    Is foobar a structure or a class If it's a structure, then what you've got is as expected. If it's a class, then there must be something going on with your setText/getText methods. For a structure (or any other value type), when adding your item to the dictionary, the entire structure gets copied over which is why you would get what you're getting. For a class, only the reference is copied over. Would that explain what you're seeing

    Imran.

  • mok

    I see. I tested this with a class that has public fields just to make sure. Works fine. If you don't mind, can you share what the code looks like in getText and setText I suspect something is going on in there..

    Imran.

  • Patrick Sears

    foobar is supposed to be a class. What you say does make sense, but the behavior is the same. They still have different values.

  • Dictionaries and the objects they contain!