I know that IDataReader
is the interface and DataReader
is the concrete type but I still don't know when to use each one. I need to iterate through the data which is possible using both Datareader
and IDataReader
. Is there a better way to decide when to use the interface or the concrete type?

- 6,050
- 1
- 33
- 56

- 4,401
- 8
- 30
- 49
-
http://stackoverflow.com/questions/6137245/c-sharp-idatareader-sqldatareader-difference – Rohit Vats Jul 20 '13 at 11:22
4 Answers
SqlDataReader
and all other data providers implement IDataReader
. If you think that you may change the provider from sql to oracle or something else in future then use IDataReader
. You will have the luxury of changing that without changing your code where you have used IDataReader
. Else you can use SqlDataReader
. But if you use IDataReader
it will be a decoupled design and is recommeneded.

- 7,243
- 6
- 49
- 61

- 31,833
- 6
- 56
- 65
You would use the Interface whenever you wanted to decouple the reading from (creating) the actual reader. For instance for testing or when you want to be prepared for switching databases.
But normally the DataReader consuming code is tightly coupled to the reader and you wouldn't bother with an interface.

- 263,252
- 30
- 330
- 514
IDataReader
is referring to an interface. Basically If your method accepts an IDataReader
that means that it will accept anything that uses that interface. This means you can use any data reader you want basically. The method will accept your datareader because the datareader implements the IDataReader
interface.
The advantage of doing this is that the method is not specific to a specific type of data reader. You could also roll your own class that implements this interface.
Referred this LINK

- 7,243
- 6
- 49
- 61

- 604
- 1
- 12
- 25
If your code doesn't absolutely positively need to know about the concrete type (for example, to use some method that is only available on the specific implementation), then I would say: refer to the interface. This makes you code far more flexible - for example, it would be trivial to add in a profiling decorator (like "MiniProfiler") which sits in the ADO.NET pipe. If you have hard-coded to SqlDataReader
, you can't do this. It also means you can change backend entirely. But frankly this is usually a huge decision and will involve significant code changes, so that scenario is less "obvious".
However, I'd also opine that most people write too much plumbing code involving ADO.NET. There are tools like "dapper", or heavier (but more feature-rich) ORMs that can do this for you, avoiding a lot of risk of human error.

- 7,243
- 6
- 49
- 61

- 1,026,079
- 266
- 2,566
- 2,900