Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
The classes in C# can now make use of the keyword "interface" to inherit more than one behavior from
different interfaces. When a class inherits from one or more interfaces, we say that the class is
implementing that interface(s). The most important thing to remember about interfaces is that the classes
can only implement the methods defined in the interface because in C#, an interface is a built-in keyword
that declares a reference type that includes method declarations. In addition to methods, interfaces can
define properties, indexers, and events that will be discussed later in this article.
Implementing Interfaces
First, we consider the following example that will clear the concept more. As we know that Mammals have
both similar and dissimilar characteristics, so in this example, we have taken two sub-classes of Mammal:
Human and Whale. Because Human is the only subclass that has the characteristic of intelligence that
distinguishes it from the other subclasses of Mammal, the Human class inherits both the class Mammal
and an interface IIntelligent that selectively describes it as separated from the other classes of Mammal.
using System;
namespace ConsoleApplication1
{
public class Mammal
{
protected string Characteristis;
public string characteristics
{
get
{
return this.Characteristis;
}
set
{
this.Characteristis=value;
}
}
}
interface IIntelligence
{
/// Interface method declaration
bool intelligent_behavior();
}
Console.Read();
}
}
}
interface IIntelligence
{
/// Method declaration within the interface
bool intelligent_behavior();
I will use the same code of the Mammal class above for explaining this. Here, we need to change only the
Main ( ) because we only need to check that our created object is either implementing the interface or
not.
if(human is IIntelligence)
{
IIntelligence humanIQ = (IIntelligence)human;
humanIQ.intelligent_behavior();
}
In the example case above, when you will run it, it will give a warning that "the given expression is always
of the provided type" and the validity is also been checked twice: one in using the "is" operator and the
other when casting it to the interface type.
Therefore, we can use the "as" operator to cast and check the types more efficiently. The "as" operator
returns an object type and null if the type mismatched whereas the "is" operator returns a Boolean value.
Here, no warning will be generated.
if(null != humanIQ)
{
humanIQ.intelligent_behavior();
}