Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Abstract" interface in C#

Tags:

This is an Academic question. There is arguably an X-Y problem behind it, which I may post separately later. But I am actually specifically interested in the Academic Question, here.


I often find that I have groups of interfaces which all have properties in common. And I want to define a base interface to commonise those, partly for lack of repetition and partly so that I can pass around an object and use the common methods without knowing the exact type.

Maybe I have IFooRepository, IBarRepository, etc., and I can declare IRepository<TEntity>.

Or I have an IHappyBot, ISadBot, IConfusedBot, all of which have IBot in common.

Notably no class would ever directly implement these base interfaces - you'd never have something that implemented just IBot.

If we were talking about a hierarchy of classes, rather than interfaces, then I would say "Ah ... the base thing is an abstract class".

Is there anything analogous that I can do with the interface to document the expectation that IBot isn't going to get directly implemented.

A aspect of it that I'm interested is doing something that you can later detect via reflection, so that when I test my DI setup, I can say "Ah, this interface isn't expected to be bindable, because it's "abstract".


I mainly care about C# myself, but if this feature specifically exists in other major languages it would interesting to hear about it.
like image 874
Brondahl Avatar asked Feb 07 '18 12:02

Brondahl


1 Answers

A philosophical question in response perhaps - But why should a class not be able to implement IBot if it wants to?

What about an abstract class? I might want an abstract base Bot class to implement IBot as a way to check that the Bot base class ticks all the functionality expected of a base Bot.

An interface is about defining what something can / should do, it's a list of functionality. In my mind it doesn't make much sense to say "something can't claim it satisfies this list of functionality".

An abstract class makes sense because sometimes the abstract class needs its implementation holes filled (abstract methods etc). This isn't the case with an interface.

like image 102
David E Avatar answered Oct 28 '22 06:10

David E