Friday, April 2, 2021

What is Interface?

The interface is used to achieve abstraction in C#. It can only contain method declarations and properties. It is a contract between two entities. 

I am using the same example from the previous post on Abstraction, to know more about what is abstraction you can visit the same post.

interface IBird        //Interface keyword to declare it
{
    void Sound();    //Only method signature
}

Points to remember,
  • Like abstract classes, no instance creation so no constructor is allowed.is allowed for Interfaces as well 
  • Declaring interface with I comes out of practice to identify the same. 
  • Interfaces can contain methods and properties but not fields
  • All members of interface are abstract and public, you do not need to use public access modifiers
  • Derived classes must have an implementation of Interface members, you do not require to use override keyword to implement the method like abstract classes
  • The interface provides security and standard contract 

class Dove: IBird                    //Inherited Interface
{
        public void Sound()        //interface method implementation
        {               
                Console.WriteLine("Coo Coo");
        }
 }

above is an implementation example of Interface IBird to Dove class. 


No comments:

Post a Comment

C# Interview Prep: 100 Common Questions for 0-3 Years Experience

Common C# Interview Questions  Basics of C# Language: What is C#? C# (pronounced C sharp) is a modern, object-oriented programming language...