I recently read in “Professional C# 4 and .NET 4” that:
You can never instantiate an interface.
But periodically I see things like this:
IQuadrilateral myQuad;
What are the limitations in using interfaces directly (without having a class inherit from the interface)? How could I use such objects (if they can even be called objects)?
For example instead of using a Square class that derives from IQuadrilateral, to what extent could I get away with creating an interface like IQuadrilateral myQuad?
Since interfaces don’t implement methods, I don’t think I could use any methods with them. I thought interfaces didn’t have fields to them (only properties), so I’m not sure how I could store data with them.
The answer is simple, you can’t instantiate an interface.
The example you provided is not an example of instantiating an interface, you are just defining a local variable of the type
IQuadrilateralTo instantiate the interface, you would have to do this:
And that isn’t possible since
IQuadrilateraldoes not have a constructor.This is perfectly valid:
But you aren’t initiating
IQuadrilateral, you are initiatingSquareand assigning it to a variable with the typeIQuadrilateral.The methods available in
myQuadwould be the methods defined in the interface, but the implementation would be based on the implementation inSquare. And any additional methods inSquarethat are not part of theIQuadrilateralinterface would not be available unless you castmyQuadto aSquarevariable.