Differences between Interfaces and Abstract Classes in C#.Net

 

Here we discuss the difference between Interface and Abstract class in C#.Net. It also explains when to use Interface and when to use abstract class.

 

When you create an interface, you are creating a set of one or more method definitions that you must write in each class that implements that interface. There is no default method code generated: you must include it yourself. The advantage of interfaces is that they provide a way for a class to appear to be part of two classes: one inheritance hierarchy and one from the interface. If you leave an interface method out of a class that is supposed to implement that interface, the compiler will generate an error.

 

When you create an abstract class, you are creating a base class that might have one or more complete, working methods, but at least one that is left unimplemented, and declared abstract. You can’t instantiate an abstract class, but must derive classes from it that do contain implementations of the abstract methods. If all the methods of an abstract class are unimplemented in the base class, it is essentially the same as an interface, but with the restriction that you can’t make a class inherit from it as well as from another class hierarchy as you could with an interface. The purpose of abstract classes is to provide a base class definition for how a set of derived classes will work, and then allow the programmer to fill these implementations in differently in the various derived classes.

 

Another related approach is to create base classes with empty methods. These guarantee that all the derived classes will compile, but that the default action for each event is to do nothing at all. Here is a Employee class like that.

 

public class Employee

{

            protected int EmpId;

            protected int Department, EmpGender;

            protected EmployeeInfo EmpInformation; 

 

            public Employee(int empId, string dept, string gender)

            {

                EmpId = empId;

                Department = dept;

                EmpGender = gender;

                EmpInformation = new EmployeeInfo(empId);

            }           

 

            public void empRole(int empId)

            {

            }           

 

            public virtual float empSal()

            {

                return sal;

            }

}

 

Note that the empRole method is now an empty method. Derived classes will compile without error, but they won’t do anything much. And there will be no hint what method you are supposed to override, as you would get from using an abstract class.