2. Interfaces are simplest construct of C#. But understanding
when and why to use them can take years…
www.dotnetvideotutorial.com
3. 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
5. 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
definition.
6. Let us try to understand using simple example.
Let us create simple interface IDemoInterface with two methods
defined in it…
www.dotnetvideotutorial.com
7. By default every member of interface is public so interface
doesn„t allow use of access modifier.
8. Interface doesn't have any implementation.
We have to implement members defined by interface
in class that we will drive from interface.
9. That‟s why we never say that
“we are deriving class from interface”
Instead we say that
“we are implementing interface in class”
10. Let us implement IDemoInterface in DemoClass
www.dotnetvideotutorial.com
11. Interface implementation syntax is same as class inheritance.
We need to implement all methods of IDemoInterface in DemoClass
12. Now we have two ways to create object of DemoClass.
17. Now let us add little complexity to our example.
Assume that there is one more interface ISampleInterface
with two methods…
www.dotnetvideotutorial.com
18. This interface have two methods fun2() and fun3().
We have intentionally kept fun2() in both the interfaces .
19. 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
20.
21. Now we have three ways to create object of DemoClass
www.dotnetvideotutorial.com
26. But in this case we have assumed that fun2() of both the interfaces
has common implementation.
Go back and check in DemoClass we have single implementation of
fun2()
27. What if we wanted to provide separate implementations for fun2()
of IDemoInterface and ISampleInterface?
www.dotnetvideotutorial.com
28. We can do it using
Explicit Interface Implementation
29.
30. Now fun2() is explicitly implemented and have two separate
implementations.
Also observe that explicitly implemented methods can‟t have
access modifier in DemoClass as they will be always public
31. We can’t call explicitly implemented methods using
reference of class.
www.dotnetvideotutorial.com
32. We can call only fun1() and fun3() using reference of DemoClass. Compiler will not able to
resolve method call to fun2() as there are two implementation on fun2() in DemoClass.