0

say I want to iterate over a list of IDs and use them to compare some properties in a QueryOver-statement as in:

foreach(int id in myIdList)
{
    QueryOver<Tabe> query = QueryOver.Of<Table>()
      .Where(t => t.SomeForeignKey == id);
}

Now my compiler advised me to create an extra variable for the iterator id, as it will otherwise be treated as a closure accessing a foreach-variable. So to be on the safe side I adjustet the code to:

foreach(int id in myIdList)
{
    int id1 = id;
    QueryOver<Tabe> query = QueryOver.Of<Table>()
      .Where(t => t.SomeForeignKey == id1);
}

And the compiler stopped complaining.

For the first version the compiler said, that the behaviour of the statement differs depending on the compiler version, so I am wondering in which cases it would be save to use the first expression and why it produces correct / incorrect results. And why is it in the end better to use the second version?

Thank you for any insights!

Philipp
  • 649
  • 2
  • 7
  • 23
  • 2
    Accessing a modified closure can cause *unexpected results*. Microsoft fixed this oversight in the C# 5 compiler. This question already has an answer [elsewhere](http://stackoverflow.com/a/13633696/2015959). – User 12345678 Sep 30 '14 at 09:58

1 Answers1

1

I suggest you to read more about Closures, you can see the more details about usage in C# at "Delegates (C#, D)" section of the link

Sergey Malyutin
  • 1,484
  • 2
  • 20
  • 44