Please ignore code readability in this question.
In terms of performance, should the following code be written like this:
int maxResults = criteria.M
Your two code samples are only guaranteed to have the same result in single-threaded environments, which .Net isn't, and if MaxResults
is a field (not a property). The compiler can't assume, unless you use the synchronization features, that criteria.MaxResults
won't change during the course of your loop. If it's a property, it can't assume that using the property doesn't have side effects.
Eric Lippert points out quite correctly that it depends a lot on what you mean by "the compiler". The C# -> IL compiler? Or the IL -> machine code (JIT) compiler? And he's right to point out that the JIT may well be able to optimize the property getter, since it has all of the information (whereas the C# -> IL compiler doesn't, necessarily). It won't change the situation with multiple threads, but it's a good point nonetheless.