C
C#•2w ago
bingham

Interface practices

Apologies for the dumb question, I've been out of C# for more than a decade, and I have the unenviable task of porting some template-heavy C++ code to C#. My googling has failed to get results because I'd call what I want to do "delegation", and, well, that name is already taken... Anyway, I've got a class that has C++ multiple inheritance, and I need to reproduce the functionality in C#. So, I add an interface to (at least one) base class, have the derived class derive from the interface, and add a field to the derived class containing the implementation of the interface. My question is -- is there a way to tell the compiler "refer this interface to this field that implements the interface" as a single... operation? concept? without writing out stubs for all methods in the interface?
7 Replies
canton7
canton7•2w ago
There's nothing in the compiler. VS will generate the boilerplate for you: you need to implement the interface, have a field of the interface type, then I think it's a code fix on the bit where you implement the interface
bingham
binghamOP•2w ago
Appreciate the reponse -- thanks for taking the time to read the question.
canton7
canton7•2w ago
(If you want to hide that boilerplate away, you can use a partial class, of course) But yeah, sadly we don't have anything a bit slicker
bingham
binghamOP•2w ago
yeah, with all of the other QoL things C# implements I'm honestly surprised there's nothing like that
canton7
canton7•2w ago
It doesn't tend to end up being an issue most of the time If you've got a member that implements an interface that others need, you normally just expose that and consumers use it directly, rather than wrapping and delegating it
bingham
binghamOP•2w ago
Yeah, in a ground-up design I'd prefer that, but I'm porting C++ and don't have as much of a test corpus as I'd like I'll refactor to sanity once the thing is working 😛
Anton
Anton•2w ago
Make a source generator for this I've been wanting to make one for more than a year I have made one before but for a custom tool rather than for the compiler framework It's like 600 loc https://github.com/AntonC9018/Zayats/tree/master/kari_stuff%2Fplugins%2FForward

Did you find this page helpful?