Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use IDataReader and when to use DataReader?

Tags:

c#

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?

like image 759
Neeraj Dubey Avatar asked Dec 12 '22 13:12

Neeraj Dubey


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

like image 57
Ehsan Avatar answered Dec 28 '22 09:12

Ehsan


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.

like image 27
Henk Holterman Avatar answered Dec 28 '22 09:12

Henk Holterman