Inheritance is a crucial concept of object-oriented programming in C#. Sometimes, interfaces or classes that are inherited have methods with common names. While programming, this can throw errors as the compiler may get confused about which function is being called.
Let's take an example and see what error occurs with common function names of inherited interfaces:
using System;class HelloWorld{interface Iinterface1{void print();}interface Iinterface2{void print();}class Example:Iinterface1, Iinterface2{public void Iinterface1.print(){Console.WriteLine("Hello World from Interface 1!");}public void Iinterface2.print(){Console.WriteLine("Hello World from Interface 2!");}}static void Main(){Iinterface1 obj = new Example();obj.print();Iinterface2 obj2 = new Example();obj2.print();}}
Lines 4 to 6: We have the first interface with a method named print()
.
Lines 7 to 9: We have the second interface with a conflicting method called print()
.
Lines 10 to 17: We have the Example
class that inherits both of the interfaces and has the implementation of the functions named print()
.
Lines 20 to 23: We declare two objects of Iinterface1
and Iinterface2
, respectively. Then, we have function calls to both objects' respective print()
methods. However, it results in an error as the compiler gets confused about which method the calls are referencing.
We can avoid this error by removing the public
keyword in the implementation of the functions:
using System;class HelloWorld{interface Iinterface1{void print();}interface Iinterface2{void print();}class Example:Iinterface1, Iinterface2{void Iinterface1.print(){Console.WriteLine("Hello World from Interface 1!");}void Iinterface2.print(){Console.WriteLine("Hello World from Interface 2!");}}static void Main(){Iinterface1 obj = new Example();obj.print();Iinterface2 obj2 = new Example();obj2.print();}}
By removing the public
keyword, we have bounded the scope of the methods to their respective interfaces. In this way, we cannot access the methods publicly from another class, and the implementation of both the print()
functions refer to the interface that contains it properly.
Free Resources