John
John

Reputation: 714

Why Datareader cannot be initialized?

we use abstract keyword before classname to restric creating the instance of a class.

But datareader is not an abstract class,but we cant create instance of that..can you explain why?

I searched about it then I found it does not have constructor that's why we cannot create object but as per my knowledge if there is no constructor then compiler automatic create a default constructor.

Please help...

Upvotes: 6

Views: 5270

Answers (2)

Troy
Troy

Reputation: 1

Just create your own class that implements DbDataReader and override the methods

public class InMemoryDbReader: DbDataReader
{
    ...
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460238

DbDataReader is an abstract class. If you mean SqlDataReader instead, it has no public constructor, that's why you can't create an instance. It has only an internal constructor (ILSpy):

// System.Data.SqlClient.SqlDataReader
internal SqlDataReader(SqlCommand command, CommandBehavior behavior)
{
    // ...
}

From MSDN:

To create a SqlDataReader, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor.

In general it is a good idea to avoid instantiating a DataReader since it needs to be created via SqlCommand.ExecuteReader only.

Upvotes: 6

Related Questions