What is a interface

C# - Interface

An interface is like a contract. In the human world, the contract between the two or more humans binds them to act as per the contract. In the same way, the interface includes the declaration of one or more functionalities. Entities that implement the interface must define functionalities declared in the interface. In C#, a class or a struct can implement one or more interfaces.
In C#, an interface can be defined using the interface keyword. Interfaces can contain methods, properties, indexers, and events as members.


Consider the following ipen interface that declares some basic functionality for a pen.
  1. interface IPen
    {
        string Color { get; set; }
        bool Open();
        bool Close();
        void Write(string text);
    }

In C#, you cannot use any access modifier for any member of an interface. All the members by default are public members. If you use an access modifier in an interface then the C# compiler will give a compile-time error "The modifier 'public/private/protected' is not valid for this item". (Visual Studio will show an error immediately without compilation.)
Example: Invalid Interface with Access Modifiers
  1. interface IPen
    {
        public string Color { get; set; }  //error
        protected bool Open(); //error
        private bool Close();  //error
        protected internal void Write(string text);//error
    }

Implementing an Interface

A class or a Struct can implement one or more interfaces using colon (:).
Syntax: <class or struct name > : <interfaces name> 
For example, the following class implements ipen interface implicitly.
Example: Interface Implementation
  1. class Cello : IPen
    {
        public string Color { get; set; }
            
        private bool isOpen = false;
            
        public bool Close()
        {
            isOpen = false;
            Console.WriteLine("Cello closed for writing!");
    
            return isOpen;
        }
    
        public bool Open()
        {
            isOpen = true;
            Console.WriteLine("Cello open for writing!");
                
            return isOpen;
        }
    
        public void Write(string text)
        {
            //write text if open
            if(isOpen)
                Console.WriteLine("Cello: " + text);
        }
    }

In the above example, the cello class implements the ipen interface. It defines all the members of the ipen interface with public access modifier. However, other non-interface members of the class can have any access modifiers e.g. isOpen field is a private member of the cello class.


















Post a Comment

0 Comments