Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Change A Property Within The Foreach Loop

Change A Property Within The Foreach Loop

Scheduled Pinned Locked Moved C#
helpcsharptutorialquestioncareer
10 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    BlitzPackage
    wrote on last edited by
    #1

    Is it ok in .Net 3.5 to change a property within a foreach loop? Does it still run the risk of producing unpredictable results? Also, will the potential results be noticeable or might it cause some type of slow, inconspicuous but nonetheless catastrophic error. For example: foreach(Employee janitor in EmployeesWithPayIncrease) { janitor.Salary += 5000; } Thanks for any help or information you can provide.

    OriginalGriffO B realJSOPR A 4 Replies Last reply
    0
    • B BlitzPackage

      Is it ok in .Net 3.5 to change a property within a foreach loop? Does it still run the risk of producing unpredictable results? Also, will the potential results be noticeable or might it cause some type of slow, inconspicuous but nonetheless catastrophic error. For example: foreach(Employee janitor in EmployeesWithPayIncrease) { janitor.Salary += 5000; } Thanks for any help or information you can provide.

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #2

      It is fine to change a property; the only thing you can't do is change the loop variable or the list itself. So

      foreach(Employee janitor in EmployeesWithPayIncrease)
      {
      janitor.Salary += 5000;
      }

      is fine, but

      foreach(Employee janitor in EmployeesWithPayIncrease)
      {
      janitor = new Employee();
      }

      or

      foreach(Employee janitor in EmployeesWithPayIncrease)
      {
      EmployeesWithPayIncrease.Remove(janitor);
      }

      are not, as it would mean it would compromise the enumeration.

      If Barbie is so popular, why do you have to buy her friends? Eagles may soar, but weasels don't get sucked into jet engines. If at first you don't succeed, destroy all evidence that you tried.

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      L 1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        It is fine to change a property; the only thing you can't do is change the loop variable or the list itself. So

        foreach(Employee janitor in EmployeesWithPayIncrease)
        {
        janitor.Salary += 5000;
        }

        is fine, but

        foreach(Employee janitor in EmployeesWithPayIncrease)
        {
        janitor = new Employee();
        }

        or

        foreach(Employee janitor in EmployeesWithPayIncrease)
        {
        EmployeesWithPayIncrease.Remove(janitor);
        }

        are not, as it would mean it would compromise the enumeration.

        If Barbie is so popular, why do you have to buy her friends? Eagles may soar, but weasels don't get sucked into jet engines. If at first you don't succeed, destroy all evidence that you tried.

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #3

        I can think of ways to make the first piece of code fail as well :)

        OriginalGriffO 1 Reply Last reply
        0
        • L Lost User

          I can think of ways to make the first piece of code fail as well :)

          OriginalGriffO Offline
          OriginalGriffO Offline
          OriginalGriff
          wrote on last edited by
          #4

          So can I! But I figure that if he is asking a basic (sensible, but basic) question like that, I didn't want to confuse him with custom comparisons, etc. I found it refreshing to be politely asked a sensible question :laugh:

          If Barbie is so popular, why do you have to buy her friends? Eagles may soar, but weasels don't get sucked into jet engines. If at first you don't succeed, destroy all evidence that you tried.

          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

          L 1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            So can I! But I figure that if he is asking a basic (sensible, but basic) question like that, I didn't want to confuse him with custom comparisons, etc. I found it refreshing to be politely asked a sensible question :laugh:

            If Barbie is so popular, why do you have to buy her friends? Eagles may soar, but weasels don't get sucked into jet engines. If at first you don't succeed, destroy all evidence that you tried.

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #5

            True I can also think of ways to make the other two pieces* of code work without (changing them, of course) But it's not like that's going to happen in the real world a lot either :) edit *: well ok only the last one, unless I'm allowed to cheat

            1 Reply Last reply
            0
            • B BlitzPackage

              Is it ok in .Net 3.5 to change a property within a foreach loop? Does it still run the risk of producing unpredictable results? Also, will the potential results be noticeable or might it cause some type of slow, inconspicuous but nonetheless catastrophic error. For example: foreach(Employee janitor in EmployeesWithPayIncrease) { janitor.Salary += 5000; } Thanks for any help or information you can provide.

              B Offline
              B Offline
              BlitzPackage
              wrote on last edited by
              #6

              Thanks for the information. I appreciate the answer. However, I am curious: how could you make the first piece of code fail? Also, my code will work without unintended consequences, right?

              L 1 Reply Last reply
              0
              • B BlitzPackage

                Thanks for the information. I appreciate the answer. However, I am curious: how could you make the first piece of code fail? Also, my code will work without unintended consequences, right?

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #7

                BlitzPackage wrote:

                how could you make the first piece of code fail

                The setter of that property could be changing the collection in some way

                BlitzPackage wrote:

                Also, my code will work without unintended consequences, right?

                Well that depends on what the property is doing..

                1 Reply Last reply
                0
                • B BlitzPackage

                  Is it ok in .Net 3.5 to change a property within a foreach loop? Does it still run the risk of producing unpredictable results? Also, will the potential results be noticeable or might it cause some type of slow, inconspicuous but nonetheless catastrophic error. For example: foreach(Employee janitor in EmployeesWithPayIncrease) { janitor.Salary += 5000; } Thanks for any help or information you can provide.

                  realJSOPR Offline
                  realJSOPR Offline
                  realJSOP
                  wrote on last edited by
                  #8

                  You can't modify an object in a foreach loop like that. You have to loop differently (for, while, etc)

                  .45 ACP - because shooting twice is just silly
                  -----
                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                  -----
                  "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                  OriginalGriffO 1 Reply Last reply
                  0
                  • realJSOPR realJSOP

                    You can't modify an object in a foreach loop like that. You have to loop differently (for, while, etc)

                    .45 ACP - because shooting twice is just silly
                    -----
                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                    -----
                    "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                    OriginalGriffO Offline
                    OriginalGriffO Offline
                    OriginalGriff
                    wrote on last edited by
                    #9

                    Yes you can - provided the property you modify does not alter the comparison, or add / remove items from the collection. Increasing the salary would not be a problem. :-D

                    If Barbie is so popular, why do you have to buy her friends? Eagles may soar, but weasels don't get sucked into jet engines. If at first you don't succeed, destroy all evidence that you tried.

                    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                    "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                    1 Reply Last reply
                    0
                    • B BlitzPackage

                      Is it ok in .Net 3.5 to change a property within a foreach loop? Does it still run the risk of producing unpredictable results? Also, will the potential results be noticeable or might it cause some type of slow, inconspicuous but nonetheless catastrophic error. For example: foreach(Employee janitor in EmployeesWithPayIncrease) { janitor.Salary += 5000; } Thanks for any help or information you can provide.

                      A Offline
                      A Offline
                      AspDotNetDev
                      wrote on last edited by
                      #10

                      When a foreach is applied to a collection, C# will have the collection return an enumerator (I believe by calling a method, GetEnumerator). With the built in .Net types, those enumerators have logic in them that throw an exception if they detect that the list has been changed since the enumerator was created. They do this by taking a snaphot of the version number stored in the collection. Whenever a collection is modified, .Net increments this version number. And whenever an element is gotten from the enumerator, it checks it's version number against the collection it was created from. The version number is only incremented for operations that change the structure of the list (reordering items, item removal, item additions, assigning items, and so on), not ones that change simple attributes of the list. Also, most programmers are not aware that this version incrementing and checking must be done, so many custom collections will not throw an exception when the collection was modified in a foreach. For example, you could yourself create a custom collection that doesn't check if the collection was modified. Then no exception would be thrown when you modify the collection (add items, delete them, etc). Whether or not modifying the collection during a foreach would cause an error (note that I didn't say "exception", I said "error") entirely depends on the collection.

                      [Forum Guidelines]

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups