Why not "new SqlDataReader()" ?

  • Thread starter Thread starter Ricola !
  • Start date Start date
Ricola ! said:
Why do I say:

SqlDataReader dr;

instead of

SqlDataReader dr = new SqlDataReader();

There are no public constructors for SqlDataReader - if you could
construct one as above, what would you expect it to read?

You have to obtain a SqlDataReader reference from a call to a method of
another class - usually SqlCommand.ExecuteReader.
 
This is because your SqlCommand object is going to return to you an instance
of SqlDataReader. You never create a datareader object yourself.

if you did the following you would have two SqlDataReader objects in memory.
and the first one would no longer have a reference to it.
SqlDataReader dr = new SqlDataReader();
dr = SqlCommand.ExecuteReader();

dr is the following case is basically a pointer. The SqlCommand return the
object that dr points to.
SqlDataReader dr

hope that clears it up for you.
Chris
 
Back
Top