C
C#4mo ago
Tom

✅ Methods (with bodies) in interfaces

Hi! C# allows interfaces to contain methods already with some implementation (i.e. with body). As I can easily think about taking advantage of this, but doesn't it deny the main reason interfaces exists - i.e. to abstract things? If it were your decision whould you use this functionality in your project or stick only to other options (like putting logic inside abstract classes, using services, etc.)?
7 Replies
Angius
Angius4mo ago
It's a contentious addition to the language, for sure The idea is it makes refactoring easier And... that's about when it should be used I'd certainly not use it as a substitute for multiple inheritance or anything like that Basically, the scenario is that you need to add some member to the interface, but that would require you to implement that member in all 67535 classes that implement the interface. That can often be a lot, so you start by implementing it in the few classes that need it right now, while the default interface implementation lets other classes not implement the member for now It should be used for placeholders, basically
Jimmacle
Jimmacle4mo ago
i see it as a tool to maintain backwards compatibility, if you have an interface that's implemented by other code, if you add methods to it you can provide a default implementation so that the consuming code doesn't immediately break
Tom
TomOP4mo ago
cool, I think I got it, thanks for explanations 🙂 btw. I had small confusion how to tag this post, can this be considered as a "beginner" question?
Jimmacle
Jimmacle4mo ago
i would say so, though i personally don't look at the post tags to decide what difficulty the question is 😛
Tom
TomOP4mo ago
😄
Jimmacle
Jimmacle4mo ago
i just go through posts and answer if it's something i know
Tom
TomOP4mo ago
good approach! thanks for your input @ZZZZZZZZZZZZZZZZZZZZZZZZZ and @Jimmacle
Want results from more Discord servers?
Add your server