Reputation: 19
I had an interview question-C#, is it possible to implement in a class, inheriting from an interface has two methods with same name and same signature?
Upvotes: 1
Views: 3188
Reputation: 5140
If I'm understanding your question correctly, yes a single class would fulfil 2 separate interfaces that have the same method signature.
However, you can also provide a different implementation for each interface. This can be referred to as 'explicit interface implementation'. For instance...
interface ITest1
{
void Test();
}
interface ITest2
{
void Test();
}
public class TestImpl : ITest1, ITest2
{
void ITest1.Test()
{
}
void ITest2.Test()
{
}
}
When using explicit interface implementation, you cannot call the method from the concrete type, i.e. new TestImpl().Test()
. You can only call the implementations specific to each interface when you have an interface-specific reference. For example.
(new TestImpl() as ITest1).Test();
(new TestImpl() as ITest2).Test();
Or...
ITest1 test = new TestImpl();
test.Test();
Upvotes: 1
Reputation: 1857
is it possible to implement in a class, inheriting from an interface has two methods with same name and same signature?
No, with implementing one interface you cannot.
is it possible to implement in a class, inheriting from interfaces has two methods with same name and same signature?
yes, Tom's answer is showing how.
But when two interface requires your class to implement a method which have same name and signature, you can also do like below.
interface ILandAnimal
{
void ToWalk();
void ToBreed();
}
interface IWaterAnimal
{
void ToSwim();
void ToBreed();
}
public class Amphibians : ILandAnimal, IWaterAnimal
{
//only one implementation of ToBreed ()
// (which is there in both interface)
public void ToBreed() { }
public void ToWalk() { }
public void ToSwim() { }
}
In most of the cases, it really doesn't matters (and also doesn't make much sense) to have two methods for two interfaces as both interfaces contract with class to implement one such method which have same name and same signature as interface contains.
and implementing only one method satisfy this contract of both interfaces.
for example : In above code, Both Land Animal's and Water Animal's interfaces require their inheritors to have a functionality to breed. And class Amphibians
does inherit both of them as it must have all functionalities of Land and water animal. Still it will have only one way (implementation) to breed. so making two methods for breeding is not required.
But this approach of implementation will not work if your class must have one behavior on interface1's method and different behavior on interface2's method. And in such cases you must go with Tom's answer
Upvotes: 0
Reputation: 191058
Not with the same interface. If you had 2 interfaces with methods with the same signature, one class implementation would fulfill both.
Upvotes: 1