An interface
is a structure that defines a template that class or interface that will inherit from must follow. It has similarities with abstract
classes. It is created using the interface
keyword.
abstract |
interface |
---|---|
Does not provide full abstraction. | Provides full abstraction. |
Can have fields. | Can’t have fields. |
Can have implementations for some of its members (methods). | Can’t have implementation for any of its members. |
Members can have access modifiers. | Members can’t have access modifiers. |
Members are private by default but can be changed. |
Members are public by default and can’t be changed. |
Can inherit from another abstract class or another interface. | Can inherit from another interface only and cannot inherit from an abstract class. |
A simple interface is created like this:
interface IMyInterface
{
// Code of your interface
}
It generally contains template methods and some properties:
interface IMyInterface
{
public string MyInterfaceProperty { get; set; } // interface can have properties
void interfaceMethod(); // interface method (does not have a body)
}
interface
can inherites from one or multiple interface.
interface IMyInterfaceParent1
{
bool interfaceParent1Method(); // interface method (does not have a body)
}
interface IMyInterfaceParent2
{
public int MyInterfaceParent2Property { get; set; } // interface can have properties
int interfaceParent2Method(); // interface method (does not have a body)
}
interface IMyInterface: IMyInterfaceParent1, IMyInterfaceParent2
{
public string MyInterfaceProperty { get; set; } // interface can have properties
void interfaceMethod(); // interface method (does not have a body)
}
/* A class that inherits from IMyInterface must override every methods and properties from the interface and its parents */
class MyClass: IMyInterface
{
public int MyInterfaceParent2Property { get; set; }
public string MyInterfaceProperty { get; set; }
public MyClass() { MyInterfaceParent2Property = 1; MyInterfaceProperty = "1"; }
public bool interfaceParent1Method() => false;
public int interfaceParent2Method() => 0;
public void interfaceMethod() { }
}
interface ISampleInterface {
void SampleMethod();
}
class ImplementationClass : ISampleInterface {
public void SampleMethod() {
Console.WriteLine("Implementation of interface method.");
}
}
ISampleInterface obj = new ImplementationClass(); // Implicit Boxing - Equivalent to 'ISampleInterface obj = (ISampleInterface) new ImplementationClass()'
ImplementationClass obj2 = (ImplementationClass)obj; // Unboxing
obj2.SampleMethod(); // "Implementation of interface method."
See: