3

I have a question. Interface does not hold any definition. Interface can not be instantiated. How can this code be valid ?

IDataReader reader = cmd.ExecuteReader()

cmdExecuteReader returns an object with a value in memory. reader is interface. How can an object be assigned to an interface ? isnt interface just a contract with no method definitions inside ?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
avast
  • 31
  • 2

3 Answers3

10

ExecuteReader doesn't return an object - it returns a reference to an object of some type which implements IDataReader (or null, of course).

The idea is that the caller/client doesn't need to know about the implementation class, just that it implements the interface. When the client calls a method such as reader.Next(), that will use the implementation based on the execution-time type of the object that the value of reader refers to.

Assigning a reference value to a variable doesn't change the type of object to which that reference refers. For example:

string text = "hello";
object o = text;

Now o and text have the same value - a reference to the same string. If you call:

Type t = o.GetType();

that will still return a reference to the Type object representing System.String, because the value of o refers to a String object; the type of the variable through which you access the object doesn't change the execution-time type of the object.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

While you can't instantiate an interface, you can instantiate objects that implement the interface. That object can then be referred to by the interface type. That is what the code above is doing.

Xhalent
  • 3,914
  • 22
  • 21
0

cmd.ExecuteReader() does not create and return an IDataReader instance; it returns an object that happens to implement IDataReader (and that may also implement any number of other interfaces). So you can assign a value to a variable or field declared as an interface type, but you cannot create an instance of an interface type.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343