Interfaces are simplest construct of C#. But understanding
when and why to use them can take years…
In this session let us focus on understanding interface as a C# construct.
We will discuss one of its usability in next session “Dependency Injection”
where we will see how we can create loosely coupled systems using interfaces
An interface contains only the signatures of
methods, properties, events or indexers.
A class or struct that implements the interface must implement the
members of the interface that are specified in the interface
Let us try to understand using simple example.
Let us create simple interface IDemoInterface with two methods
defined in it…
By default every member of interface is public so interface
doesn„t allow use of access modifier.
Interface doesn't have any implementation.
We have to implement members defined by interface
in class that we will drive from interface.
That‟s why we never say that
“we are deriving class from interface”
Instead we say that
“we are implementing interface in class”
Let us implement IDemoInterface in DemoClass
Interface implementation syntax is same as class inheritance.
We need to implement all methods of IDemoInterface in DemoClass
Now we have two ways to create object of DemoClass.
Normal Instantiation: Using reference of DemoClass only
Now let us add little complexity to our example.
Assume that there is one more interface ISampleInterface
with two methods…
This interface have two methods fun2() and fun3().
We have intentionally kept fun2() in both the interfaces .
C# allows multiple interface implementation.
Let us implement both the interfaces in DemoClass
Imp Note: Multiple class inheritance is not allowed in C#. i.e. we can‟t derive
class from two or more classes
Now we have three ways to create object of DemoClass