Click here to Skip to main content
15,034,598 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have done lots of search regarding this answer and I've come up with conclusion mentioned below.

I want to know whether it is a fairly enough and a justified reason for choosing one over the other?

What I have tried:

Use abstract class when we have some default functionality or methods whose definition will remain same for all
the sub-classes. So by using abstract class, we do not have to write same code again and again, even in future if
we need to change the functionality we just need to make changes at a single place.
Posted
Updated 7-May-18 0:54am
v2

   
Comments
CPallini 7-May-18 6:53am
   
5.
Maciej Los 7-May-18 7:51am
   
Thank you, Carlo.
The simplest answer is that when we have some default behaviors that will be same for every derived class which would be inheriting from the base type then abstract class is suitable as we can define method with implementation that will be re-used by child classes too. While for interface we only define the signatures which means that it only tell what kind of behaviors it expects to be provided when some type is implementing it.

Note that in newer version of C# we would be able to define methods with default implementation in interfaces too.

You can also refer to the following threads for more clarity:

Abstract Class versus Interface

Interfaces vs. abstract classes
   
v4
Comments
knackCoder 7-May-18 7:12am
   
From your answer and mine doubt above, I'm understanding that "providing default functionality in base class" is something which determines whether we should go for Interface or a Abstract class; right?
Ehsan Sajjad 7-May-18 8:14am
   
in most of the cases yes, otherwise it does not makes sense to have abstract class, but mind that there are no hard and fast rules, but in general practice interfaces is preferred in situation where there is no default behavior needed but just contract.
BillWoodruff 7-May-18 10:52am
   
+5 good answer, and I bet the "Gang of Four" would have nightmares about the idea of any "implementation" in Interfaces: this idea is a proposed feature of C# 8, and we don't know whether it will be implemented.

See: https://dotnetcoretutorials.com/2018/03/25/proposed-default-interface-methods-in-c-8/
Ehsan Sajjad 7-May-18 11:19am
   
Thanks @Bill and yes it is not yet out as part of C# 8

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900