Create object for list in or out of while loop?

I am very new to .net and am being taught by someone in the office. I have become accustomed to do this:


while (dreader.Read())
{
	UserDetails userDetails = new UserDetails();

	userDetails.Title = (string)dreader["Title"];
	userDetails.Forename = (string)dreader["Forename"];
	userDetails.Surname = (string)dreader["Surname"];

	team.Add(userDetails);
}

My question is, is there any benefit to instantiating a new userDetails object in every loop, or can this be created outside the loop and title, forename and surname just written over with every pass of the loop?

Is it more efficient to recreate the object over and over or re fill it?

cheers

monkey.

NightStalker

cheers night stalker, I thought that may be the case (and could have tested it out myself come to think of it! :))

cheers

The intentions are more clear if you instantiate in the loop rather than outside of it.
If I see code like this:


UserDetails userDetails;
while (reader.Read())
{
    userDetails = new UserDetails();
    [...]
}

I’d refactor it.

Either way, I don’t think it has an affect on performance since the compiler normally would take care of optimizations like this.

You have to do it inside the loop. As if it is a generic list or some other container that uses pointers under the covers. If you declair it outside the loop, every item in the list will have the same values, as it will just be adding a pointer to the object in the list and that object will change. If that makes sense.

It is not resource intensive at all to init new objects, unless your doing heavy stuff in their constructors