Why not "new SqlDataReader()" ?

J

Jon Skeet [C# MVP]

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.
 
C

Chris, Master of All Things Insignificant

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top