In this post, we will discuss Interface in C# and Why should we use Interface in c#. Learn about the interface in c# with real time example. I hope this will be very helpful for developing real-time projects for freshers as well as experienced people.
What is the need for Interface in c#? Why use Interface?
- It is used to Decouple the application.
- It is very useful for Dependency Injection.
- It is useful for Test isolation and Mocking.
- It is used for Extensibility
What is Interface in C#?
- An interface can contain only the declaration of properties, methods, events, indexers etc.
- Interface member does not have the definition.
- Interface member is by default Public. We can not provide access modifier to the interface member.
- We can inherit more than one interface in a class. Once we inherit interface in a class, we must provide a definition to the interface member.
- An interface cannot contain fields, operators, instance constructor, etc.
In order to work with the interface, we use the "Interface" keyword to create an interface. We can provide "I" as an interface naming prefix for interface names like IVendor, ICustomer etc.
We can not provide access modifiers, static, sealed and abstract keywords to the interface member.
Create an interface which has a name like IVendor as follows.
Now, we need to create a class to implement interface member. Create a class which has a name like Vendor as follows.
We can call the vendor class member by creating an instance of vendor class from the main method. Define the main method to access the vendor detail. There is one method, "GetVendorName()", based on vendorId as shown in the above example. In the same way, we have created one property for user permission. Based on the vendor we can provide the access to the user.
How to implement more than one interface in a class.
Create two interface names as "IVendor" and "IUserPermission". Copy the above example and paste it into a separate class. Create one more interface "IUserPermission" interface having one property and remove the property used in IVendor interface. Paste into the newly-created interface; i.e., "IUserPermission". There are no major changes.
This is the example to understand how to implement more than one interface in a class.
We will discuss the type of interface and real-time use of the interface in part two of this series.I hope you understood the basic concept of interface.
More information please watch the video as follows: