What is Interface in C# and Where to Use it.

Introduction:  In this article we will discuss about interface in C# i.e. What is interface, when, where and why to use an interface. It is one of the mostly asked interview question.

In one of my previous article on C# i explained When, where and why Private Constructor is used in C#

Interface is very similar to class. By using interface keyword we can create interface. Interface is a contract between class and interface; within interface we can put method definition but not declaration. If we try to provide declaration then it will produce compile time error. Actually interface is build planner.

How?
Because within interface we declare task only but not declaration.Means interface is boss and all employees associated with that boss are classes, If boss assign a task then all employees are responsible to define that task.


Example
namespace ConsoleApplication
{
    class Program
    {
        interface ICustomer
        {
            void Print() //It will give error: Interface members can’t have definition
            {
                Console.WriteLine("welcome");
            }
        }      
        }
        class MyProgram
        {
            static void Main(string[] args)
            {         
            }
       }
}

Question: Can we put field like integer, string, double etc. in interface?
Answer: No we can’t declare because interface can’t contain fields.

Example

namespace ConsoleApplication
{
    class Program
    {
        interface ICustomer
        {
            int i; // Interface can’t declare fields.
            void Print();           
        }      
        }
        class MyProgram
        {
            static void Main(string[] args)
            {            
            }
       }
}
Just like a class interface also contains properties, methods, delegates or event, but only declaration not implementations.

If a class or struct inherits from an Interface, It must provide implementation for all interface members. Otherwise, we get a compiler error.  Inheriting classes are responsible to define all the methods.

Example

namespace ConsoleApplication
{
    class Program
    {
        interface ICustomer
        {           
            void Print();           
        }
        class Customer : ICustomer// Implementing Interface
        {
class Customer : ICustomer // Implementing Interface
            {
                public void Print();    // Error- Two Interfaces having same 
                                       //Method  Name.Program.Customer.Print()
                                       //
 must declare a body because it is not
                                      // marked abstract, extern, or partial
               
            }      
        } 
     }
        class MyProgram
        {
            static void Main(string[] args)
            {            
            }
       }
}

All the members are public by default, and they don’t allow explicit access modifiers.

Example

class Program
        {
             interface ICustomer
            {
             public void Print(); // Error- The modifier 'public' is not
// valid for this item
            }
            class Customer : ICustomer// Implementing Interface
            {
                public void Print()// declaring that function
                {
                    Console.WriteLine("Print interface");
                }
            }
        }

A class can implement number of interfaces at the same time, but a class can’t inherit from more than one class at the same time.

Example

namespace ConsoleApplication
{
    class Program
    {
        interface I1
        {
            void I1Method();
        }
        interface I2
        {
            void I2Method();
        }
        class Customer : I1,I2  // Implemented more than one Interfaces
        {
            public void I1Method()
            {
                Console.WriteLine("I1Method Print");
            }
            public void I2Method()
            {
                Console.WriteLine("I2Method Print");
            }
        }
    class MyProgram
    {
        static void Main(string[] args)
        {
        }
    }
}
}

Now if we implements more than one class then

Example

namespace ConsoleApplication
{
    class Program
    {
        public class SampleClass1
        {
        }
        public class SampleClass2
        {
        }
        class Customer : SampleClass1, SampleClass2 // cannot have multiple base classes
        {
        }
    class MyProgram
    {
        static void Main(string[] args)
        {
        }
    }
}
}

Interfaces can inherit from other interfaces. A class that inherits this interface must provide implementation for all interface members in the entire interface inherit chain.

Example

namespace ConsoleApplication
{
    class Program
    {
        interface I1
        {
            void I1Method();
        }
        interface I2 : I1
        {
            void I2Method();
        }
        class Customer : I2  // Implementing  I2  Interface
        {
            public void I1Method() //Customer' does not implemented
                                    //interface member 'Program.I2. I2Method()
            {
                Console.WriteLine("I1Method Print");
            }
        }
    class MyProgram
    {
        static void Main(string[] args)
        {
        }
    }
}
}

I2 inherited from I1 and I1 interface and Customer class is inherited from I2 So Customer class is responsible to define all the members of I1 and I2 inherited chain.
We can’t create instance of an Interface because Interfaces are incomplete. It contains signature of method but not declaration, but an interface reference variable can point to a derived class object, Because we know that in inheritance chain a base class reference variable can point to derived class object similarly it also apply for Interface.

Explicit Interface Implementation

If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation. Then you can invoke like this.
When we have two interface I1 and I2 having same Interface Method() then Customer class implementing both I1 and I2 Interface then how we call method of I1 and method of I2.

Example
namespace ConsoleApplication
{
    class Program
    {
        interface I1
        {
            void InterfaceMethod();
        }
        interface I2
        {
            void InterfaceMethod();
        }
    
class Customer : I1, I2
{
void I1.InterfaceMethod() //Explicitly method call
{
  Console.WriteLine("I1 Method Print");
}
void I2.InterfaceMethod() //Explicitly method call
{
  Console.WriteLine("I2 Method Print");
}

class MyProgram
{ 
static void Main(string[] args)
{
Customer c1 = new Customer();
((I1)c1).InterfaceMethod();
((I2)c1).InterfaceMethod();

//OR you can use like this
 I1 objI1 = new Customer();
 I2 objI2 = new Customer();

 objI1.InterfaceMethod();
 objI2.InterfaceMethod();
}
}
    }
}

Note: when a class explicitly implements, an Interface member, the interface member can no longer be accessed thorough class reference variable, but only through the interface reference variable.
Access modifiers are not allowed on explicitly implemented interface members
  
Where to Use an Interface:
Suppose you are a build planner and you have planned a project. Then you should create an interface and declare there all your signature of method. Now derived class is free to define that function or task in own style.

Real life example: 
IPL match is an Interface and all players bought by IPL are classes. Now IPL have defined some task for all player like Playing(), Batting(), Bowling(), Fielding(), Keeping() etc.
Now all player is responsible to define that task in own style because they have signed a contract with Interface (Means with IPL). They can’t denied that implementations. 

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..