1

I'm still learning much about immutability and when to use such objects and have started incorporating more Lookups into my coding for the fact that I knew them to be immutable and, hence, often better to use than Dictionaries that could be changed by clients.

That being said, I know there has been a good deal of work on introducing ReadOnlyDictionaries into .Net and I'm a bit confused where each would be more useful than the other and what specifically makes them different. I've looked online, but can't seem to find any articles explaining this difference.

For example, I saw this question and figured a Lookup would be a more ideal solution, but am confused as to why it wouldn't be.

Can anyone point me in the right direction / explain where either would be used over the other.

Thanks!!

Community
  • 1
  • 1
John Bustos
  • 19,036
  • 17
  • 89
  • 151
  • 2
    Lookup is a mapping of a key to multiple values, whereas a dictionary is a key to one value. Not related to immutability, but they aren't exactly the same data structure. – Jacob Aug 22 '16 at 19:31
  • It sounds like you want to know why to make it readonly? The answer is the same for anything that should not be changed by an outside or private actor, ie. why make something/anything readonly. It is not specific to a dictionary and I would say its really an opinionated question. – Igor Aug 22 '16 at 19:33
  • I'm more confused as to why there even is a ReadOnlyDictionary when it seems a lookup is basically already performing that job. – John Bustos Aug 22 '16 at 19:35
  • Can you post a link to this `Lookups` type you are referring to? – Igor Aug 22 '16 at 19:35
  • 1
    Have you looked at [this answer whats the point of lookup](http://stackoverflow.com/a/1403499/1260204) or [this answer dictionary vs. lookup](http://stackoverflow.com/a/5659080/1260204) ? One difference is a lookup is allowed to have multiple values per key, a dictionary cant. – Igor Aug 22 '16 at 19:40
  • Thanks, @Igor, I guess what I'm wondering also is, in terms of immutability, would a lookup be in any way worse to use (more possibility of mutability) than a ReadOnlyDictionary? – John Bustos Aug 22 '16 at 19:44

1 Answers1

5

Lookups are an easy way to group collections, where you could have one or more values for a given key. A Dictionary gives you one value for a give key, and one value only. Depending on your scenario, it may make most sense to have a Dictionary where you get back one value, or you may want to have a Lookup which would give you a collection of values.

Without a Lookup if you wanted a collection of values for a certain key you'd be stuck with something ugly like

Dictionary<int, IEnumerable<String>>

Yuk. See https://msdn.microsoft.com/en-us/library/bb460184%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 for more on Lookups.

J. Allen
  • 602
  • 1
  • 7
  • 24