Interface


Interface represents a contract that must be implemented by a non-abstract class or a struct.

  • It is declared using the interface keyword.
  • It can only have the signatures without any implementations.
  • It may define static members.
  • It may define a default implementation.
  • It can inherit from one or more base interfaces.
  • A class or struct can implement multiple interfaces.
  • It is like an abstract class with only abstract members.
  • It can contain properties and methods, but not fields or variables.
  • It can't contain instance fields, instance constructors and finalizers, but can contain static constructors, fields, constants, and operators.
  • Its members are public by default.
  • Its members can be either public or abstract.
Example
namespace MyConsoleApp
{
    interface ILanguage
    {
        public string Country { get; set; }
        void Greeting();
    }

    class Language: ILanguage
    {
        public string country = "USA"; //Field
        public string Country //Property
        {
            get { return country; }
            set { country = value; } 
        } 

        public virtual void Greeting() //Method
        {
            Console.WriteLine("Hello!");
        }
    }
}
Execute
namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ILanguage lang = new Language();            
            Console.WriteLine("Country: " + lang.Country);
            Console.Write("Greeting: ");
            lang.Greeting();
            /* OUTPUT:
               Country: USA
               Greeting: Hello!
            */
        }
    }
}