tarun kumar
Suppose class is implementing two interfaces and both the interfaces have function name Todo() with same signature. How to implement these functions in class?
By tarun kumar in OOP/OOD on Apr 14 2024
  • Jayraj Chhaya
    Apr, 2024 30

    To implement functions with the same signature from multiple interfaces in a class, you can use explicit interface implementation. By prefixing the interface name before the method, you can disambiguate between the two methods.

    1. using System;
    2. interface IInterface1
    3. {
    4. void Todo();
    5. }
    6. interface IInterface2
    7. {
    8. void Todo();
    9. }
    10. class MyClass : IInterface1, IInterface2
    11. {
    12. void IInterface1.Todo()
    13. {
    14. Console.WriteLine("Implementation of Todo from IInterface1");
    15. }
    16. void IInterface2.Todo()
    17. {
    18. Console.WriteLine("Implementation of Todo from IInterface2");
    19. }
    20. }
    21. class Program
    22. {
    23. static void Main()
    24. {
    25. MyClass obj = new MyClass();
    26. ((IInterface1)obj).Todo();
    27. ((IInterface2)obj).Todo();
    28. }
    29. }

    MyClass implements both IInterface1 and IInterface2 with separate implementations of the Todo method for each interface. By casting the object to the respective interfaces, you can call the specific implementations.

    • 0
  • Aman Agarwal
    Apr, 2024 29

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS