Thread: foreach Dictionary

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    foreach Dictionary

    Hello everyone,


    If we use foreach to iterate a Dictionary, it is only restricted that we can not insert new elements and remove exsting elements of the Dictionary.

    And we are free (allowed) to change the content (mmber fields) of object pointed by the "value" reference of a key, right? Example,

    Code:
    foreach (KeyCollection<> k in someDictionary)
    {
        // some operation will change the member fields of related object instance
        // pointed by "value" refernece of the related key k
        someDictionary[k].someOperation();
    }

    thanks in advance,
    George

  2. #2
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,130
    If you iterate over all keys, then get the value from the dictionary to do some operation on it, why don't you get all values in the first place ?

    And yes, only changing the container will break the iterator, manipulating the contents will not. As there is no const-correctness in C# and the compiler does not know which statement changes an objects state and which does not, foreach would have no use otherwise.
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. SortedDictionary v.s. Dictionary
    By George2 in forum C# Programming
    Replies: 2
    Last Post: 06-09-2008, 08:58 PM
  2. memory footprint of Dictionary
    By George2 in forum C# Programming
    Replies: 1
    Last Post: 05-17-2008, 08:39 AM
  3. class Dictionary
    By madsiro in forum C# Programming
    Replies: 1
    Last Post: 04-20-2008, 02:52 PM
  4. I'm not THAT good am I?
    By indigo0086 in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 10-19-2006, 10:08 AM
  5. spell check in C using a dictionary file
    By goron350 in forum C Programming
    Replies: 10
    Last Post: 11-25-2004, 06:44 PM