Please go through my previous article for better understanding on Abstract Class:
I got a lot of feedback on my previous article and some users are desperately waiting for this one. I will try to incorporate all the requirements and especially when and where to use Abstract class and Interface.
Let us start with Interface now.
Interface
Readers might have heard about runtime polymorphism. Interface is the perfect example to achieve runtime polymorphism. Interface behaves like a class but with no implementation of its methods. Interfaces defines properties, methods, delegates, and events which are the members of the interface. Interfaces contain only the declaration of the members. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
- interface MyInterface
- {
- void DefineYourMethodsDefination();
- }
- Let’ s see the details example of Interface with complete implementation:
- Here is my Interface
- interface MyInterface
- {
-
-
-
- public int MyProperty
- {
- get;
- set;
- }
-
-
-
-
- void DefineYourMethodsDefination();
-
-
-
-
- event EventHandler DoSomething;
- }
Let us see the implementation in the class as well below,
Now we move on and see a few important things about “interface,” let’s take it one by one.
- Try creating instance of Interface,
So that means we can’t create an object of an Interface.
- No need to provide access modifiers,
In case you will try to do so, you will get the following error,
That means by default everything inside Interface is Public.
- I have already explained how we can define Methods, Properties, and Events in the Interface.
- Now when it comes to Inheritance, there is no other way to implement inheritance except Interface in C#.
I have two interfaces and I am implementing both below,
- public class Implementinterface: MyInterface, MyInheritInterface
- {
- public int MyProperty
- {
- get
- {
- return MyProperty;
- }
- set
- {
- MyProperty = value;
- }
- }
-
- public void DefineYourMethodsDefination()
- {
- Console.WriteLine("Hi Nishant");
- Console.ReadLine();
- }
-
- public event EventHandler DoSomething;
-
- public void ActiveDoSomething()
- {
-
- if (DoSomething != null)
- {
- DoSomething("Nishant", null);
- }
- }
-
-
-
- public void ImplementInheritance()
- {
-
- throw new NotImplementedException();
- }
This is all about interface. In the next article will explain the scenarios when we have to go for Interface and when we have to go for Abstract Class.