Thursday, 16 June 2016

Class Vs Interface in C#

Hi,

We all hear Class and Interface words through our IT Career. Here are some important notes about.
An Interface is a Contract - We specify methods and properties in it and a class implements it. Interface doesn't have any implementations.

In a very simple words we can say Interfaces are used to enforce certain Methods/Properties. In a nutshell- an interface is a set of rules. Using the interface clearly states my intent to only use members of the interface. A class can be used to inherit/override base functionality.

For example, an Animal is a class of living things, and a Lion is a class of animals. Inheritance expresses this relationship: an Lion is an Animal where Giraffe inherits from Animal. It can do anything an animal can do and more.

We cannot create an instance of Interface. The only way to "Create an instance of a interface in c#" is to create an instance of a type implementing the interface. The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.

Here is the small example

We can call DoSomeThing using objClass1 or objClass2 objects like below.
Complete Program

Output

I would prefer to write the same code like below. We can pass Interface as a type like below
Depending the object you pass you get the different behavior.
In the above example, ThisMethodShowsHowItWorks the parameter it expects is of type IIamInterface. This can take anything that implements the variable.

Hope this helps.
--
Happy Coding
Gopinath

No comments:

Post a Comment