Best practice for creating objects used in for/foreach loops

Posted by StupidDeveloper on Stack Overflow See other posts from Stack Overflow or by StupidDeveloper
Published on 2010-03-15T13:38:22Z Indexed on 2010/03/15 13:39 UTC
Read the original article Hit count: 132

Filed under:

Hi!
What's the best practice for dealing with objects in for or foreach loops? Should we create one object outside the loops and recreate it all over again (using new... ) or create new one for every loop iteration?
Example:

foreach(var a in collection)
{
  SomeClass sc = new SomeClass();
  sc.id = a;
  sc.Insert();
}

or

SomeClass sc = null;
foreach(var a in collection)
{
  sc = new SomeClass();
  sc.id = a;
  sc.Insert();
}

Which is better?

© Stack Overflow or respective owner

Related posts about c#