From Zero to Master — C# Interfaces in under 15 minutes.

You Must have some knowledge of C#


A little bit of theory

A Scenario

Lets say the animals are Cat and Dog. We can create a method called “Feed” which will feeds cat or dog but when we create a method for “Speak” the things get little complicated because the dog will bark and the cat will meow.

You may want to serve dog with dog food and cat with cat food but lets keep the things simple for learning purpose and assume that both Cat and Dog or any other animal in this read would eat the same food :)

Lets Start Programming With a Standard or Concrete Class

So lets look at the child Class Dog

now lets create the object of Dog class

when we run this program we will get

output of program.cs

Abstract Class

Lets create an AbstractAnimalClass

Driving Cat.cs from AbstractAnimalClass.cs

Lets create the object of Cat class and run the program

and here is the output

output from Dag and Cat class objects

Comparing Standard or Concrete Classes with Abstract Classes

In Standard Classes we have shared Implementation if we don’t over ride a virtual method in child classes it will use the implementation of parent class

If you are clear with above concepts then we are ready to jump into learning interfaces if not you can seek my help leave a comment and i will try to explain with a few more ways :)

Getting Started with Interfaces

Lets create or Animal Interface.

Lets introduce a new animal “Loin” and implement this interface

lets create the Loin object in program.cs

and here is the Output

We have seen here that how to create a concrete class, abstract class and an Interface. Same like abstract class the Interface implementation requires every member of the interface to be implemented if we don’t implement any member of our Interface it will give a compiler error.

Abstract Classes Vs Interface Vs Concrete Class

Abstract Class can have some non abstract member methods which can contain implementation while interfaces won’t contain any implementation at all.

Abstract Classes and Interfaces requires the Implementation of abstract members.

Class can only inherit from a single base class but a class can implement any number of interfaces.

Interfaces can not include Constructor, Destructors and Fields.

Abstract Class Members have access modifiers but Interfaces are always public.

Wow now you know what are interfaces next thing to read will be that how Interfaces help us produce testable and extensible code.

Thank you for reading :) please leave your comments if you have any questions or suggestions.

download the code from here :

MS in CS | MS in IS | Start Up Founder |Boomtown Alumni. I am always doing something in the hope that answers will follow.

MS in CS | MS in IS | Start Up Founder |Boomtown Alumni. I am always doing something in the hope that answers will follow.