Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   C# Interfaces (http://www.go4expert.com/articles/c-sharp-interfaces-t29993/)

usmanmalik 6Feb2014 11:52

C# Interfaces
 
C# owes Java a lot: In terms of features and compilation strategy C# is very similar to Java. As a matter of fact, C# was developed with intent to compete Java. However, platform dependence and less portability of C# give Java edge over C#, Interfaces are one of the many features that C# inherited from Java. This article explains what interfaces basically are and how they are used in C# .NET. What are their advantages and where should they be used.

What are Interfaces?



Interfaces are often time confusing. People do not understand why interfaces are necessary because functionalities provided by interface can also be achieved via classes. However, this is not wholly true. Interfaces have their own distinct identity and they perform distinct function which justifies their existence in C# language.

Interfaces are similar to classes but all of the interface members only provide specification rather than concrete implementation as is the case with classes. There are two key differences between classes and interfaces.
  1. All of the members of interface are implicitly or by default abstract which means that class that implements the interface has to provide implementation for all the members of the interface. On the other hand, classes have some members abstract where as others concrete.
  2. Classes and structs can inherit from multiple interfaces whereas class only inherit from single interface and inheritance in case of struct is not possible except from System.ValueType. Simply, we can say that multiple inheritance is possible from interfaces but not from classes.
Declaring an interface is similar to declaring a class but the members will be abstract. Interface can have methods, properties, events and indexers as abstract. These are the members that can be abstract in class as well.

Syntax

Syntax of the interface is simple. You have to use the keyword interface followed by the interface name as follows
Code:

public interface GoForExpert
{
    string FindExpert();
    string FindArticle();
    string WriteArticle();
}

You can see that declaring interface is much like a class where keyword class has been replaced by interface. Inside the body of the interface, we have declared three methods but we have not implemented anything. The class that implements interface will have to provide the implementation of these methods.

Now let’s see a more realistic example of how classes implement interfaces. System.Collections namespace contains an interface named IEnumerator. The definition of IEnumerator interface is as follows
Code:

public interface IEnumerator
{
    bool MoveNext();
    void Reset();
    object Current
    { get; }
}

The interface has two methods MoveNext and Void Reset() and one property of type object, named Current. A very important thing to note here is that the members of interface are public by default. Therefore, there is no need to explicitly define the scope of the interface members. Consider Example1, to see how we implement and use the IEnumerator interface in our code.

Example1

Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpTutorial
{
    public class StopWatch : IEnumerator
    {
        int time=11;
        public bool MoveNext()
        {
            return time-- > 0;
        }
        public object Current
        {
            get { return time; }
       
        }
        public void Reset()
        {
            time = 11;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IEnumerator en = new StopWatch();

            while (en.MoveNext())
            {
                Console.Write(en.Current);
            }
            en.Reset();
            Console.WriteLine(" ");
            while (en.MoveNext())
            {
                Console.Write(en.Current);
            }

            Console.ReadLine();
        }
    }
}

Let’s jump to the start of the Example1. First we import the System.Collections namespace in code via using. Next, we declared a class that implements the IEnumerator Interface via this line

public class StopWatch : IEnumerator

It can be seen that implementing an interface is similar to that of inheriting a class. Inside the body of the StopWatch class, what we have done is that we have provided the implementation for all of the methods and properties of IEnumerator class. This is necessary. Always remember that when a class implements an interface, it actually enters into a contract with that interface that it will implement all the member of the interface. Therefore, if a class is implementing interface, it will implement all the members of interface no matter whether it needs them or not.

Therefore in Example1, the MoveNext method basically decrement the integer time which is member of the class stop. The method will keep returning true until the time is greater or equal to 0. The current property will return the time and the Reset() method will again reset the time to 11. This way we are actually developing a StopWatch class.

Inside the main class we created an instance of IEnumerator interface and stored the object of StopWatch class in that via these lines

IEnumerator en = new StopWatch();

I know these lines are confusing for you. But a thing worth remember here is that we can store the object of the class in the instance of interface which the class implements. Here StopWatch class implements the IEnumerator interface; therefore, we have stored the object of StopWatch class in the en instance of the IEnumerator interface.

Then we have simply called the MoveNext method inside the while loop. The loop will execute until the time reaches 0. Inside the loop we have printed the value of time by calling en.Current which actually calls the getter of Current property that will return the time. Next, we have again called the Reset method that will reset the time to 11 and finally we again call the MoveNext method to display the values. This is the simplest demonstration of usage of interface. The output of Example1 is as follows.

Output1

http://imgs.g4estatic.com/c-sharp/interface/output1.png

Interface Inheritance



Interfaces can also inherit from other interfaces for example
Code:

public interface I1
{
    void Display();
}
public interface I2 : I1
{
    void Show();
}

Here in the above code, 12 is inheriting I1. Now when a class implements I2 it will have to implement both the show() method of derived interface I2 and the Display method of parent interface I1. This way, an interface can inherit as much interfaces as it can.

Inheriting Multiple Interfaces

As aforementioned, you can inherit from multiple interfaces in C#. This is extremely easy. You only have to separate all the interfaces that you are inheriting with a comma. For instance you have a class name ClassA that inherits two interfaces: interface1 and interface2. You can simply inherit both of them like this

public class ClassA : interface1, interface2 {}

Class that inherits or implements multiple interfaces will have to implement all the members of those interfaces. The concept of multiple inheritance has been explained with the help of following example. Have a look at Example2.
Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpTutorial
{
    public interface interface1
    {
      void Display();
    }
    public interface interface2
    {
        void Show();
    }
    public class ClassA : interface1, interface2
    {
        public void Display()
        {
            Console.WriteLine("This method belongs to interface1");
        }
        public void Show()
        {
            Console.WriteLine("This method belongs to interface2");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ClassA classa = new ClassA();
            classa.Display();
            classa.Show();

            Console.ReadLine();
        }
    }
}

In Example2, we have created two interfaces named interface1 and interface2. The interface1 has one method display and the interface2 also has one method called show. Next we have a class which implements both of these methods. The class provides the definition of both of these methods. Now, if a class only provide the definition for Display method of interface1 and leaves the show method, the compiler will generate an error that class doesn’t implement the method of interface that it implements. The code will not be compiled in that case. Therefore we have to implement all of the members of all the interfaces we inherit. This way a class can inherit virtually unlimited number of interface. The output of Example2 is as follows.

Output2

http://imgs.g4estatic.com/c-sharp/interface/output2.png

What if interfaces have methods with same name?

An interesting situation arises when multiple interfaces being implemented by a class have members with same name. What should be done in those cases? Suppose we have a method named Display with return type void in interface1 and we have another method Display with return type integer in interface2. Which method would be called when we call the Display method from the object of the class that implements both of these interfaces? Here an important concept comes to play which is known as Explicit Interface Implementation. We will explain Explicit Interface Implementation with the help of Example3. Have a look at the code in Example3.

Example3

Code:

using System.Linq;
using System.Text;

namespace CSharpTutorial
{
    public interface interface1
    {
      void Display();
    }
    public interface interface2
    {
        int Display();
    }
    public class ClassA : interface1, interface2
    {
        public void Display()
        {
            Console.WriteLine("This method belongs to interface1");
        }
        int interface2.Display()
        {
            Console.WriteLine("This method belongs to interface2");
            return 10;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ClassA classa = new ClassA();
            classa.Display();

            interface1 i1 = (interface1)classa;
            i1.Display();

            interface2 i2 = (interface2)classa;
            Console.WriteLine(i2.Display());

            Console.ReadLine();
        }
    }
}

We have modified Example2 to fit our need for explaining explicit interface implementation. You can see that we have two interfaces: interface1 and interface2 where interface1 contains a Display method that returns void and an interface2 also contains Display method which returns integer. ClassA implements both of these interfaces and inside the class definition we have provided definition for both of these functions. Notice that ClassA implements the Display method of interface one in normal way but the Display method that returns integer has been defined in a slightly different manner. The definition of Display method that belongs to interface2 and returns integer is done in the following way

int interface2.Display()

Here the interface name has been prefixed with the method name to stress that this Display method belongs to interface2. This is called explicit interface implementation where we have explicitly mentioned the name of the interface with that of its member. There is no need to define the scope of explicitly implemented interface because it is public by default.

Now coming towards the main method: We have created an object classa of ClassA; now if we call the Display method on this object, which Display Method would be called? The answer is, the Display method which has not been explicitly implemented would be called. Hence, the Display method which returns void would be called.

A point worth noticing here is that, in order to call the member of the explicitly implemented interface, we have to cast the object of the class that implements that interface, to the instance of the interface. In Example3, we have done this in the following line.
Code:

    interface2 i2 = (interface2)classa;
    Console.WriteLine(i2.Display());

We have casted the object classa into interface2 type and then stored the casted value into instance i2 of the interface. Next we have called the method from the i2 instance of interface2. The method will be executed and the value 10 will be returned and displayed on the screen. We cannot call the explicitly implemented interface members from ordinary class object. However, we can call both explicitly and inexplicitly implemented interface member from the interface instance as we have done in Example2 where Display method of interface1 is not explicitly implemented in the class body but we can call it from the interface instance of interface1 i.e i1 in the following way.
Code:

  interface1 i1 = (interface1)classa;
  i1.Display();

The output will first contain result of the method execution of Display from the interface1 via class object and then via instance of interface1. Then the output will display the result of Execution of method Display from interface2 via instance of interface2. The method will first display “This method belongs to interface2” and then it will return 10 which will be displayed on output screen via Console.WriteLine. The output of Example3 is as follows.

Output3

http://imgs.g4estatic.com/c-sharp/interface/output3.png

Interfaces, if used intelligently are extremely powerful C# features. People often confuse them with classes; however they have totally different functionality. I would advise you to further explore interfaces. In case if you have any query regarding interfaces, you can leave a reply and I will be back as soon as possible. Happy Coding!


All times are GMT +5.5. The time now is 07:47.