C# Explicit Interface Implementation

In this blog, I will create a sample to explain the concept of explicit interface implementation in C#.
C# doesn't support multiple inheritance but it supports implementing multiple interfaces. Multiple inheritance had an issue if the 2 base classes had the same function name and signature, then derived class will not know which one to call. It also adds complexity in terms of casting, field access, serialization, identity comparisons, reflection, generics etc. Interfaces don't have function body but if 2 implemented interfaces have same function name and signature and we want to make sure that the 2 interfaces are implemented separately - we can do so by using explicit interface implementation. Since interface functions have no body, if we just use the default implementation, it will also work as the requirement of implementing the method for both interfaces is already met. When we do explicit interface implementation, we can call that method only when we cast the class instance to that interface instance. Calling it on class instance will give a compilation error. The code is provided below;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            LangConverter lc = new LangConverter();
            //default way
            Console.WriteLine(lc.Convert("Default implementation"));

            // explicit french
            IFrenchConverter f = (IFrenchConverter)lc;
            Console.WriteLine(f.Convert("French implementation"));

            // explicit spanish
            ISpanishConverter s = (ISpanishConverter)lc;
            Console.WriteLine(s.Convert("Spanish implementation"));


            Console.ReadLine();
        }
    }

    public interface ISpanishConverter
    {
        string Convert(string word);
    }

    public interface IFrenchConverter
    {
        string Convert(string word);
    }

    public class LangConverter : ISpanishConverter, IFrenchConverter
    {
        // implicit implementation - return the same word
        public string Convert(string word)
        {
            return word;
        }

        // explicit implementation
        string ISpanishConverter.Convert(string word)
        {
            // lookup spanish dictionary
            return "spanish";
        }

        // explicit implementation
        string IFrenchConverter.Convert(string word)
        {
            // lookup french dictionary
            return "french";
        }
    }
}
The output is shown below:



No comments: