Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am reading/learning about interfaces in C# at the moment, and thus far I manag

ID: 643370 • Letter: I

Question

I am reading/learning about interfaces in C# at the moment, and thus far I managed to understand how it differs from an abstract class. In the book I am reading the author explains that interfaces are the ultimate abstract class and that it simply sets the standard of certain methods the inheriting class will have, but then provides the following example.

static void Main(string[] args)
{
...
Circle c = new Circle("Lisa");
IPointy itPt = null;
try
{
itPt = (IPointy)c;
Console.WriteLine.(itPt.Points);
}
catch (InvalidCastException e)
{
Console.WriteLine(e.Message);
}
...
}
The line that absolutely throws me off is the IPointy itfPt=null; did he just declare an interface? I thought interfaces are abstract and can only be inherited? What kind of sorcery is going on here?

Explanation / Answer

That example demonstrates a try...catch more than anything.

Interfaces are types too.. but they only expose their contract. So this:

IPointy itPt = new IPointy();
..won't work. Consider this:

interface IPointy {
void MyMethod();
}

class Pencil : IPointy {
void MyMethod() {
}

void MyOtherMethod() {
}
}
You can declare an IPointy like this:

IPointy itPt = new Pencil();
..however, this will work:

itPt.MyMethod();
..this won't work:

itPt.MyOtherMethod();
This is because MyMethod is part of the IPointy contract.. MyOtherMethod isn't.. Hopefully that helps.

EDIT: Expanding this to explain my comment.

Inheriting from a class represents an "is-a" relationship. Implementing an interface represents a "can-do" relationship.

Consider:

interface ISwitchable {
void SwitchOn();
void SwitchOff();
}

class Light : ISwitchable {
void SwitchOn() { }
void SwitchOff() { }
}

class Television : ISwitchable {
void SwitchOn() { }
void SwitchOff() { }
}
Both a Television and Light inherit from ISwitchable.. which is fine. The interface defines a "can-do" relationship.. they can both be switched on orr of. Both of the following blocks of code are valid:

ISwitchable mySwitchableObject1 = new Light();
ISwitchable mySwitchableObject2 = new Television();

mySwitchableObject1.SwitchOn(); // calls Light's SwitchOn method
mySwitchableObject2.SwitchOn(); // calls Television's SwitchOn method