articles

Home / DeveloperSection / Articles / Interface in C#

Interface in C#

Anonymous User4666 05-May-2016

Interface is also a user define type but can contain only abstract methods in it. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. 


Note: We are inheriting a class from to another class but it is possible to inherit the class from an interface also where as if a class inherits from another class it is for consuming the member of parent class but a class inheriting from interface is per implementing the members of its parent. 


Declaring Interfaces : Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Following is an example of an interface declaration:


Interface1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace OopsConcepts
{
   publicinterface  Interface1
   {    
     void showTransaction();
     double getAmount();     
   }
}

Implementation of the above interface

InterfaceTest class 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace OopsConcepts
{
   public class InterfaceTest:Interface1
    {
      private string tCode;
      private string date;
      private double amount;
 
      public InterfaceTest()
      {
         tCode = " ";
         date = " ";
         amount = 0.0;
      }
 
      public InterfaceTest(string c, string d, double a)
      {
         tCode = c;
         date = d;
         amount = a; 
      }    
     
      public double getAmount()
      {
         return amount;
      }
     
      public void showTransaction()
      {
         Console.WriteLine("Transaction: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
         Console.WriteLine("Amount: {0}", getAmount());
      }
    }
}

InterfaceClassTest class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace OopsConcepts
{
    classInterfaceClassTest
    {
        staticvoid Main(string[]args)
        {
           InterfaceTest t1 = newInterfaceTest("001", "8/10/2015", 78900.00);
           InterfaceTest t2 = newInterfaceTest("002", "9/10/2016", 451900.00);
       }
     }
}


Output: 1. Transaction- 001

           Date- 8/10/2015

           Amount-78900



Output: 2. Transaction- 002

           Date- 9/10/2016

           Amount-451900


Updated 24-Nov-2019
I am a content writter !

Leave Comment

Comments

Liked By