Saturday 26 September 2015

Working on Interfaces

I would like to give some brief idea about interfaces.
Example 1:
using System.IO;
using System;

class Program
{
    static void Main()
    {
        sampleclass sample = new sampleclass();
        sample.operation();
        phase1 ph = (phase1)sample;
        ph.operation();
phase2 ph2 = (phase2)sample;
ph2.operation();
    }
}
interface phase1
{
void operation();
}
interface phase2
{
void operation();
}
class sampleclass:phase1,phase2
{
  public void operation()
  {
      Console.WriteLine("Here is the operation");
  }
}

Output:
Here is the operation
Here is the operation
Here is the operation

Description: In the above code we are implementing interfaces methods in sampleclass. As we can not create the instance of interface, we are making use of sampleclass object.
Here operation() method implementation is common for phase1,phase2 interfaces.
If we have different implementations for both interfaces, lets see below example2:
=====================================================================
Example 2:

using System.IO;
using System;

class Program
{
    static void Main()
    {
        sampleclass sample = new sampleclass();
        phase1 ph1 = (phase1)sample;
        phase2 ph2 = (phase2)sample;
        ph1.operation();
        ph2.operation();
     
    }
}
interface phase1
{
void operation();
}
interface phase2
{
void operation();
}
class sampleclass:phase1,phase2
{
  void phase1.operation()
  {
      Console.WriteLine("Here is the Phase1 method");
  }
  void phase2.operation()
  {
      Console.WriteLine("Here is the Phase2 method");
  }
}

Output:
Here is the Phase1 method
Here is the Phase2 method

Description: Here we are implementing same method in different ways. For that we are using interface name then period(.) and method name.

Hope this gives little idea regarding interfaces :)

No comments:

Post a Comment