1. Back To Blog

C# and .NET interview question - How will you implement interface with same method name in C#?

C# and .NET interview question - How will you implement interface with same method name in C#?

This is one of the typical .Net interview questions and is also the favorable question of interviewers.


Let's first try to understand what exactly the question means.


Suppose we have two interfaces namely I1, I2 and both the interface have a single method with same name like below code snippet.




In above code snippet you can see that we have two interfaces with same method name.


Now, let's create a class which inherits both interfaces I1, I2 and also do the implementation like below code snippet.


In above code snippet you can see that I have implemented method only once.



Now let's see if this compile or not.




You can see that the compile successfully, this means that we have not break any of the rule.

Now, let invoke both the interfaces method in main class like below code snippet.




Now, just run the application and you will see result like below diagram.




The above code works fine but our concern is to have two different for both the interfaces. So in order to achieve this we have to "ExplicitInterface" method implement.

Now, let's see how exactly we can achieve this practically.

Step1: - create a new console application for that Go To> New > File > Project > Windows > Select Console Application.






Step2: - create two interfaces like below code snippet.




Step3: - create a class which inherits both the interfaces and implement both the interfaces methods like below code snippet.




In above code snippet you can see that I have used "ExplicitInterface" method implementation.




Step4: - now just invoke both the interfaces methods in the main class like below code snippet.




Once you have done with all the above steps now just run your application and you will see the result like below diagram.




Now from the above result you can see that both Interfaces methods are having different implementations.

View the following video how can we implement interfaces with same method names in C#: -





Also see our tutorials onDotnet interview questions and answers

Regards,

View more author's blog on Most asked Dotnet interview questions
 
 

Shiv Prasad Koirala

Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social