This is an awesome c# interview question. Kudos to the interviewer who has asked this c# question and double kudos to the candidate if he answers this c# question.
The biggest use of interface is to ensure that strict CONTRACT is followed between clients and components. So that when changes happen on the components clients do not have to change too much. In real world CONTRACTS between two parties do not change which implies that interfaces should also not change.
So if you want to add new methods or change methods in interfaces the best practice is to create new interfaces by inheriting. With this approach your older client who are using the interface stay happy and the new clients who want those new or changed methods get the benefit of the new functionality.
Let’s consider you have a simple interface called as “IView” which helps you to view data , below is the code for the same. Let’s consider that this interface is consumed by many clients.
public void View();
Over a period of time some users demand “Edit” functionality as well but the rest of the users are happy with the ‘View” functionality and they do not want to get affect by these changes. Now if you go and change this interface ( “IView”) a.k.a you will be disturbing everyone.
So the best option would be to add a new interface i.e. “IEdit” which inherits from “IView”. So the “IEdit” will have the functionality for “Edit” as well as “View” because it’s also inheriting from “IView”. And the clients who are consuming “IView” do not need to update as “IView’ is not changed at all.
interface IEdit : Iview
public void Edit();
Answering this c# interview question in simple sentence.
Interface once fixed should not be changed. If we ever have to add new functions, new interfaces should be created so that we do not break compatibility with old clients.
Recently one of our friends was asked an awesome c# interview question, how can we debug c# threads?. Click on this video to see how we can debug threads
Taken from the best selling c# and .NET interview question book, you can see more about the book by clicking on interview questions and answers for .NETHere’s our site for interview questions and answers for .NET
Click to view more from author’s on C# and interview questions and answers for Dotnet