Difference between Abstract class and Interface in C#.NET
I often encounter the situation to discuss the deference between Interfaces and abstract class when I have been to Interviews. Well, .NET have many new Object Oriented features among those Interfaces and abstract class are important.
Interface in C#:
An Interface is not a class, we can say it an entity or a template that is define by the word Interface. We cannot instantiate the Interface and it is just like implementing the polymorphism. An interface should not contain any code in it only method signature should be there.
Below code snippet describes the Interface declaration in C# code.
public interface IMyInterface
{
int UserId { get; set; }
string Description { get; set; }
string UserPhoneNumber(int phoneNumber);
event EventHandler userStatus;
string this[int userIndex] { get; set; }
} Abstract Class in C#:
Abstract class is just like as normal class but which cannot be instantiated. It means we cannot create an object for the Abstract class. An abstract class starts with the Keyword Abstract. It contains concrete and abstract members. A concrete method may have the implementation but abstract member should only have the signature.
Below is the sample code snippet to define the abstract class.
public abstract class TestAbstract
{
private int testAbstractId;
public abstract void MyTest(int i);
public abstract string this[int Myindex] { get; set; }
public abstract string MyDescription { get; set; }
public TestAbstract(int testAbstractIdValue)
{
testAbstractId = testAbstractIdValue;
}
public int TestAbstractId
{
get
{
return testAbstractId;
}
set
{
testAbstractId = value;
}
}
} Difference between Abstract Class and Interface :
Abstract Class:
1) Abstract class is a class which cannot be instantiate.
2) Abstract class may have both concrete and abstract members, i.e we may have the implementation and we may not have the implementation in case of abstract members.
3) Multiple inheritances are not supported in case of Abstract class.
4) It is a kind of contract that enforces all the derived classes to carry on the same hierarchies or standards
5) A class does not implement the multiple abstract classes. Interface:
1) Interface is a template which cannot be instantiate.
2) Interface should have only abstract members and without implementation.
3) Multiple inheritances are supported in case of Interfaces.
4) To implement the same method in the all derived classes.
5) A Class can call the multiple Interfaces.
Better approach is been provided for .NET beginners.