However, a base class is usually a "thing" (noun) e.g. Control in the previous post on abstract base classes.
An interface is usually a "capability" e.g. Enumerable, or Readable, Storable, etc.
You can implement as many interfaces as you like, to simulate multiple inheritance. (C# doesn't support multiple inheritance of classes).
Interfaces don't have access modifiers - they aren't legal. By definition an interface has to be public.
Casting
You can't create an instance of an interface but you can create a variable of an interface that points to an instance of a class that implements the interface. (Just like you can create a variable of an abstract base class that points to an instance of a concrete class). You may wish to cast that variable into the type of class that it points to. There are several ways to do this, the safest is the as keyword.The as keyword
var myClass = new ImplementingClass();ICapability capable = myClass;
ImplementingClass theNewClass = capable as ImplementingClass;
if (theNewClass != null)
{
//do something class specific;
}
If the cast fails the variable will be set to null so you must always check that.
No comments:
Post a Comment