Interface, Explicit Interface Implementations in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 2896 red flag
Rating: 5 out of 5  
 1 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read Struct, properties of structs in C# before this article.

Introduction

So far, we have studied about structs in C#. Now let's get into another interesting topic 'interface' in this chapter.

Objective

The main objective of this article is to learn interfaces and explicit interface implementations in C# programming.

Interface

Interfaces are similar to class which contains the signatures of properties and methods. Instead of implementation, it provides the specification to its members. Differences between interface and class are as follows,
InterfaceClass
All the members of an interface are implicitly abstract.Class can have abstract as well as concrete members with implementations.
Here, a class can implement multiple interfacesHere, a class can implement the members from a single class.
Structs can implement multiple interfacesSince struct is a value-type, it cannot inherit any classes or structs.

Need of Interface:
  1. In order to use classes, methods, properties, events etc. in unified way, we will go for interfaces. By using interfaces, we can share these codes.
  2. Using interfaces makes program little complex but, that complexity provides great simplicity. They will make the programs easier to maintain and more compact.
Declaration:
Interface declaration is similar to a class declaration without any implementations for its members. That is,
interface MyInterface
{
    void MyMethod();   // Abstract method
}
Observe that we have only abstract method MyMethod in the above interface MyInterface. This method will be implemented by the classes or structs who implements this interface. For example,
class MyClass : MyInterface
{
    public void MyMethod()  // implemented from MyInterface
    {
        Console.WriteLine("This is implemented Function"); // prints the message
    }
}
In the above code, we are implementing MyInterface members to MyClass.
  • Interfaces can have only properties, methods, events and indexers which should be abstract.
  • Interface members cannot declare any access modifiers as they are always public implicitly by default. If we do, it will throw run time error. Example,
    interface MyInterface
    {
        public void MyMethod();  // This will throw run time error.
    }
    The above method will gives error like,

  • Interfaces usually named after the letter 'I' such as IExample, ITest etc. to understand easily and to avoid the confusion from class-inheritance. Naming convention is not mandatory.
  • If a class or struct implements an interface, it should return all the members of that interface. If not, it will throw a run time error.
Example:
Let's have a neat example of using interfaces in C#,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {
        interface IExample                // Declaring Interface
        {
            void Test();
            void Repeat();
        }

        class MyClass : IExample          // MyClass implementing IExample interface
        {
            public void Test()
            {
                Console.WriteLine("This is the method implemented from IExample interface.");
            }
            public void Repeat()
            {
                Console.WriteLine("This is the Repeat() method");
            }
        }

        static void Main()
        {
            IExample my = new MyClass();
            my.Test();                    // Calling Test() method

            IExample rep = new MyClass();
            rep.Repeat();                 // Calling Repeat() method
        }
    }
}
  • In the above example, we have an interface IExample with two abstract methods Test() and Repeat()
  • We declared a class MyClass which implements  IExample interface.
  • We should implement all the members of IExample in the MyClass.
  • Finally in the Main method, we are casting an object implicitly to IExample because, it has been implemented by MyClass.

    Note: Its not mandatory to call all the implemented members of MyClass from the Main method.
The output of this example code will prints something like below in your console,


Implementing Multiple Interfaces

We already know that, a class or a struct can implement multiple interfaces. For example, if we have have an interface like below,
interface IFirst
{
    void One();
}
and another interface like,
interface ISecond
{
    void Two();
}
Now, in order to implement two interfaces, we have to follow the below declaration,
class MyClass : IFirst, ISecond // Implementing multiple interfaces
{
    // IFirst member
    public void One()
    {
        .........;
    }
    // ISecond member
    public void Two()
    {
	.........;
    }
}
This is how we can implement multiple interfaces at once.

Explicit Interface Implementation

Let's have a scenario that a class is implementing two interfaces having same member signatures in both of them. This will result in a collision between both the member signatures.

To avoid this type of collisions, we have to implement an interface member explicitly. This process is called as Explicit Interface Implementation.

Example:
Let's have a clean example that explains Explicit Interface Implementation,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {
        interface IExample1              // IExample1
        {
            void Test();
        }

        interface IExample2              // IExample2
        {
            void Test();
        }

        class MyClass : IExample1, IExample2  // Implementing multiple interfaces
        {
            public void Test()
            {
                Console.WriteLine("This is Test of Example1");
            }

            void IExample2.Test()             // Explicit implementation
            {
                Console.WriteLine("This is Test of Example2");
            }
        }

        static void Main()
        {
            MyClass my = new MyClass();
            my.Test();                  // This will call IExample1.Test()

            ((IExample2)my).Test();     // Using Cast
        }
    }
}
In the above code, we have two interfaces IExample1 and IExample2 with same signature Test(). In this case, we have to implement the members explicitly like IExample2.Test() in our case. This will avoid the collision and conflict between both methods and allows to reside in the same class.

There is only one way to call the explicit implemented member. That is to cast to its interface. Observe that we have used cast for calling the explicit method i.e. ((IExample2)my).Test() 

By using this mechanism, we can also hide the members that are distracting to normal use case.

If you run the above code in your console, it will print the below lines,


Conclusion

In this article, we have studied interfaces and explicit implementation of interfaces in C# programming language. Hope you understand.

Thanks for reading.

Regards,
Krishna.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)