views:

80

answers:

1

In the below shown examples, the former approach instantiates an object of type SearchResult for each iteration whereas the latter one instantiates the object only once and uses it for all the iterations.

using (DbDataReader reader = (DbDataReader)dbObject.ExecuteReader(command))
        {
            if (reader.HasRows)
            {
                List<SearchResult> searchResults = new List<SearchResult>();
                while (reader.Read())
                {
                    SearchResult searchResult = new SearchResult();
                    searchResult.AppName = Convert.ToString(reader["AppName"]);
                    searchResults.Add(searchResult);
                }
            }
        }

OR

using (DbDataReader reader = (DbDataReader)dbObject.ExecuteReader(command))
        {
            if (reader.HasRows)
            {
                List<SearchResult> searchResults = new List<SearchResult>();
                SearchResult searchResult = new SearchResult();
                while (reader.Read())
                {                        
                    searchResult.AppName = Convert.ToString(reader["AppName"]);
                    searchResults.Add(searchResult);
                }
            }
        }

Which is the better approach to handle this?

Thanks and kindly ignore my naiveness. :)

+5  A: 

The first approach is better as the 2nd one won't work as intended as you're using the same instance each time and over writing the property. You're going to end up with a List of SearchResult's with all the same value! So definitely the first version.

You need to use the first version or instantiate a new instance each time like this:

SearchResult searchResult;
while (reader.Read())
{
      searchResult = new SearchResult();
      searchResult.AppName = Convert.ToString(reader["AppName"]);
      searchResults.Add(searchResult);
}

EDIT This is of course assuming SearchResult is a class, if it is in fact a struct then it is a value type and this will not be a problem

w69rdy
^^ ok, but I am changing the value of the properties and adding the instance to the list within a common scope, so why would it result in same values for each list item?
Dienekes
Because you're using the same instance of SearchResult each time, and adding the same reference to the List, so changing the property on that instance changes it for all in the list as they reference the same instance
w69rdy
@Dienekes: Because objects are reference types, when you only have one object (because you only declare one object) even though you insert it multiple times into a List, or Array, or whatever, all you're really doing is ending up with several different references to the same location in memory: that is, multiple references to the same obect.
AllenG
How do you know SearchResult is class and not struct?
jethro
@jethro Because I can read minds ;)
w69rdy