TheAlbear
TheAlbear

Reputation: 5585

How to convert/cast SqlDataReader to IDatareader

What is the easiest way to cast a SqlDataReader to IDatareader.

Or is it easier / possible to convert a List<> object to a IDataReader

Upvotes: 7

Views: 5977

Answers (4)

Jeff Sternal
Jeff Sternal

Reputation: 48593

A SqlDataReader is an IDataReader (it implements the interface), so you don't have to convert it at all. Anywhere your code expects an IDataReader, you can use the Sql implementation.

// Given a method with this signature
public void ProcessData(IDataReader reader);

// You can do this
SqlDataReader sqlReader = command.ExecuteReader();
ProcessData(sqlReader);

As for List<T> and IDataReader: apart from being enumerable these do very different things. The most conspicuous difference is that data readers offer access to columnar data (primarily because it implements the IDataRecord interface), which doesn't make sense for most lists.

You could implement an adapter that provides access to a List<T> through the data reader interface, but it would be a poor fit and a fair amount of work.

Upvotes: 3

Brad
Brad

Reputation: 15577

Or you can just cast it, but as has been stated, it's largely unnecessary unless you're creating or using a generic interface since all the properties and methods of IDbDataReader is available to SqlDataReader.

((IDbDataReader)typedReader).SomeMethod();

Upvotes: 1

TomTom
TomTom

Reputation: 62093

What is the easiest way to convert a SqlDataReader to IDatareader

You can not. A SqlDataReader CLASS is not an IDataReader interfadce.

For casting (assign to variable) use

IDataReader untypedReader = typedReader; 

BUT: this is NOT a conversion. It is a cast. A conversion to an inteerface is per defintiion not possible as interfaces can not be instantiated.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062855

What is the easiest way to convert a SqlDataReader to IDatareader

Since SqlDataReader implements IDataReader, this is just an implicit cast:

SqlDataReader typedReader = ...
IDataReader untypedReader = typedReader;

Upvotes: 10

Related Questions