1.

How to work with Interfaces in C#

Answer»

The definitions for different functionalities that classes can inherit are contained in INTERFACES in C#. All the interface members are only declared in the interface and they need to be defined in the class that derives them.

The keyword interface is used for interface definition. Usually the interface names BEGIN with a capital I because of common convention. Since multiple inheritance is not allowed in C#, interfaces are quite useful when a class needs to inherit functionalities from multiple sources.

A program that demonstrates working with interfaces in C# is given as follows:

using System; namespace Demo {    public interface IEmployee    {      void display();    }    public class Employee: IEmployee    {        private int empno;        private string name;        public Employee(int e, string n)        {            empno = e;            name = n;        }        public void display()        {            Console.WriteLine("Employee Number = {0}", empno);            Console.WriteLine("Name = {0}", name);            Console.WriteLine();        }    }    class Test    {      static void MAIN(string[] args)      {         Employee e1 = new Employee(101, "James");         Employee e2 = new Employee(102, "Susan");         Employee e3 = new Employee(103, "Bella");         e1.display();         e2.display();         e3.display();      }    } }

The output of the above program is given as follows:

Employee Number = 101 Name = James Employee Number = 102 Name = Susan Employee Number = 103 Name = Bella


Discussion

No Comment Found