Search This Blog

Monday 28 December 2015

Interface in C#

interface IWatch
{
      void Model();
}

class CasioWatch : IWatch
{
      //Interface Method Implementation in derived class
      public void Model()
      {
           Console.WriteLine("Model(): Casio Watch model LA680WGA-1BVT");
      }

      //Derived Class Local Method 
      public void ArrivalDate()
      {
           Console.WriteLine("ArrivalDate(): This Watch arrival date not yet confirm.");
      }
}

class Program
{
      static void Main(string[] args)
      {
           CasioWatch obj = new CasioWatch();
           obj.Model();
           obj.ArrivalDate();

           Console.ReadLine();
      }
}

Output
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4-BGVSpKsrpo4xOAuNuOkryZQsHkq95Qr03uDHQKwSgPVzeEN3CbMBq2x2E9GwdFfsXqLb_9w9pFwJ3KpqaufU6EKTnEIROuSD791g5u0Vi8S4nZh5XK8gZ_O3z3KQANhf6HJf2c2nH0/s400/img.png

Tips

1. An Interfaces have all abstract methods.
Ex.
interface IWatch
{
     void Model();
}

2. An Interfaces cannot be sealed or static.
Ex.
sealed interface IWatch
{
}

3. An Interfaces access modifiers cannot be private, protected, or protected internal.
Ex.
private interface IWatch
{
}

4. An Interfaces methods, properties, events or indexers declaration doesn’t have access modifiers.
Ex.
interface IWatch
{
     public string ModelNo { getset; }
     public void Model();
}

5. An Interfaces declared with interface keyword.
Ex.
interface IWatch
{
}

6. An Interfaces cannot contain fields but contains only the signatures of methods, properties, events or indexers.
Ex.
interface IWatch
{
     //string ModelNo = ""; // Error
     string ModelNo { getset; }
     void Model();
}

7. An Interfaces method cannot be marked virtual.
Ex.
interface IWatch
{
     string ModelNo { getset; }
     virtual void Model();
}

8. An interface members cannot be static.
Ex.
static string ModelNo { getset; }
static void Model();

9. We cannot change return type, when implementing the interfaces method in derived class.
Ex.
//Interface Method
void Model();

//Interface Method Implementation in derived class
public int Model()
{
     Console.WriteLine("Casio Watch model A55");
}

10. We cannot create an instance of the abstract class or interface but we can create a reference to its derived classes.
Ex.
interface IWatch
{
      //Interface Method
      void Model();
}

class CasioWatch : IWatch
{
      //Interface Method Implementation in derived class
      public void Model()
      {
           Console.WriteLine("Casio Watch model A55");
      }
}

class Program
{
      static void Main(string[] args)
      {
            IWatch obj = new IWatch(); // This Line generate Error

     IWatch obj = new CasioWatch(); // OK
}
}

11. An interface members cannot have a definition or body.
Ex.
//Interface Method
void Model()
{
}

12. A Base class or Derived class can inherit more than one interface.
13. A Derived class must implement interface member.

No comments:

Post a Comment