Why do both the abstract class and interface exist in C#?

前端 未结 11 1975
渐次进展
渐次进展 2020-12-03 00:00

Why do both the abstract class and interface exist in C# if we can achieve the interface feature by making all the members in the class as abstract.

Is it because:

11条回答
  •  猫巷女王i
    2020-12-03 00:27

    It's not a trivial question, it's a very good question and one I always ask any candidates I interview.
    In a nutshell - an abstract base class defines a type hierarchy whereas an interface defines a contract.

    You can see it as is a vs implements a.
    i.e Account could be an abstract base account because you could have a CheckingAccount, a SavingsAccount, etc all which derive from the abstract base class Account. Abstract base classes may also contain non abstract methods, properties and fields just like any normal class. However interfaces only contain abstract methods and properties that must be implemented.

    c# let's you derive from one base class only - single inheritance just like java. However you can implement as many interfaces as you like - this is because an interface is just a contract which your class promises to implement.

    So if I had a class SourceFile then my class could choose to implement ISourceControl which says 'I faithfully promise to implement the methods and properties that ISourceControl requires'

    This is a big area and probably worthy of a better post than the one I've given however I'm short on time but I hope that helps!

提交回复
热议问题