Why Interfaces in C#

Consider the following code snippets-

// Code for the IAccount interface module.
 public interface IAccount
 {
   void PostInterest();
   void DeductFees(IFeeSchedule feeSchedule);
 }
 class BusinessAccount : IAccount
 {
   void IAccount.PostInterest()
   {
   // Code to post interest using the most favorable rate.
   }

   void IAccount.DeductFees(IFeeSchedule feeSchedule)
   {
   // Code to change a preferred rate for various services.
   }
 }

A very general question is- Why not just have the class BusinessAccount and two functions in it PostInterest() and DeductFees()?

Answer is: using Interfaces in C#, we can create types that support multiple behaviors. In the above example, if you did not implement the interface, if you had another class with methods PostInterest and DeductFees, you would have to check for type before converting them to their type and then calling their methods. With the Interface, you only need to cast it to the interface (if it is not passed as the interface type) before calling the methods.
Interfaces allow to create nice layouts for what a class is going to implement. When many components use the same interface it allows us to easily interchange one component to another which is using the same interface. Dynamic programs can be easily created with this feature.

This entry was posted in C#, Knowledge Sharing, Troubleshooting. Bookmark the permalink.

4 Responses to Why Interfaces in C#

  1. Awesome post. Incredibly refreshing given all the duplicate content out there. Thanks for doing something original.

  2. You could definitely see your expertise in the paintings you write. The world hopes for even more passionate writers such as you who aren’t afraid to say how they believe. Always follow your heart.

  3. Hi there, You have performed an incredible job. I’ll certainly digg it and personally suggest to my friends. I am confident they will be benefited from this site.

Leave a Reply