Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c#, interface, assignment

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 ?

like image 899
avast Avatar asked Sep 06 '25 10:09

avast


2 Answers

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.

like image 93
Jon Skeet Avatar answered Sep 08 '25 01:09

Jon Skeet


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.

like image 27
Xhalent Avatar answered Sep 08 '25 00:09

Xhalent