Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have Read An interface cannot be instantiated directly in MSDN

but there only while giving an example they are instantiating it like this

SampleClass obj = new SampleClass();
//obj.Paint();  // Compiler error.
IControl c = (IControl)obj;
c.Paint();  // Calls IControl.Paint on SampleClass.
ISurface s = (ISurface)obj;
s.Paint(); // Calls ISurface.Paint on SampleClass. 


where IControl and ISurface are interfaces and paint is method which is defined in SampleClass which inherits these two interface

My question is
IControl c = (IControl)obj;
here also they are creating an instance of IControl
so wheter interface can be instantiated or not??
please guide me..
Posted

Not really sure what your question is, but that bottom line shows the SampleClass instance being casted as an IControl and then assigned to an IControl variable. Actually, the compiler is smart enough to know when a class implements an interface, so the explicit cast is not necessary. You could just write:
C#
IControl c = obj;

It is correct to say interfaces cannot be directly instantiated, as they are not really classes (they are just interfaces that some class must implement). You can then create an instance of a class that implements the interface, then assign that instance to a variable of the interface type. For example, you could have also done this:
C#
IControl c = new SampleClass();
c.Paint();

Now, if you wanted to assign that to an ISurface variable, you would have to explicitly cast it:
C#
ISurface s = (ISurface)c;

I recommend you do some reading (a book or some tutorials online) about object oriented programming, perhaps specifically as it relates to C#.
 
Share this answer
 
IControl c is not really an instance of IControl, but an instance of SampleClass casted to IControl.
 
Share this answer
 
v2
nishuthegreat wrote:
My question is

IControl c = (IControl)obj;

here also they are creating an instance of IControl
so wheter interface can be instantiated or not??


No, they create a reference to an object implementing the interface.
:)
 
Share this answer
 
In the MSDN example, they have declared a variable of type IControl and assigned it an instance of the concrete class that implements IControl.
 
Share this answer
 
Comments
CHill60 12-Oct-15 10:59am    
Post was answered over 5 years ago! You have added nothing to the existing solutions

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900