Question

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

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

Was it helpful?

Solution

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;

OTHER TIPS

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.

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.

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top