I have two classes B
and C
which share a common property a
of type D
.
class B
{
public D a {get;set;}
public E b {get;set;}
}
class C
{
public D a {get;set;}
public F c {get;set;}
}
I could make a
abstract class A
{
public D a {get;set;}
}
from which B
and C
inherits.
class B:A
{
public E b {get;set;}
}
class C:A
{
public F c {get;set;}
}
I also know that I will have a service with a method GetValue
which returns an object of type A
.
interface Service
{
A GetValue();
}
The class A
could also be an interface but then the property a
had to be implemented double by B
and C
. The question is should I use interface
or abstract
for implementig A
? To inherit from abstract class just for the reason that two classes have a common property seems to be not a good practice, but I am not sure.
CodePudding user response:
You can reflect both the common property a
and method GetValue()
in an abstract class. Keep in mind that in C your function signature cannot return abstract type. I also don't see how an interface could do anything for you in your example, as it would simply be empty.
CodePudding user response:
If you're using C# > 8.0 then you can create an interface with a default method implementation. This way you don't have to have an abstract class but at the same time you don't need to re-implement the shared method.