C# Tutorials
C# Methods
C# Classes
C# Examples
Another way to achieve abstraction in C#, is with interfaces.
An interface is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies):
// interface
interface Animal
{
void animalSound(); // interface method (does not have a body)
void run(); // interface method (does not have a body)
}
In order to access interface methods, the interface must be "implemented" (as if inherited) from another class. To use the interface, use the : symbol (as an asset). The body of the interaction is given the “implement” class. Note that you do not need to use the override keyword when using the interface:
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
To implement multiple interfaces, break them up with commas:
interface IFirstInterface
{
void myMethod(); // interface method
}
interface ISecondInterface
{
void myOtherMethod(); // interface method
}
// Implement multiple interfaces
class DemoClass : IFirstInterface, ISecondInterface
{
public void myMethod()
{
Console.WriteLine("Some text..");
}
public void myOtherMethod()
{
Console.WriteLine("Some other text...");
}
}
class Program
{
static void Main(string[] args)
{
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}