[Proposal] simplify forwarding (easier composition) #7296
-
Composition is a very good alternative to inheritance and many people prefer it, but one of the major downsites of composition is a lot of boilerplate code due to forwarding methods of the inner type. I propose a way to select methods from a property or field that should be automatically forwarded. The syntax could be something like this: from field forward foo1, foo2; for example this: internal sealed class Example{
private Test Composited {get; init;} = new();
from Composited forward Try, Force;
} would be equivalent to this: internal sealed class Example{
private Test Composited { get; init; } = new();
internal void Try()=> Composited.Try();
internal void Force()=> Composited.Force();
} This massively reduces boilerplate. forward field;
//alternatively
from field forward all; After thinking about this it might be a bad idea:
blacklisting could also be usfull forward field exclude foo3;
// or
from field forward all exclude foo3; override forward might also be usfull from field override forward ToString; forwarding all methods from an interface that the type implements might also be usefull from field forward IReadonlyField Notes
Benefits
Drawbacks
Alternativesusing attributes[Forward] private T property {get; set;}
[Forward(foo1, foo2)] private T property {get; set;} appending to property/field definitionprivate T Property {get; set;} forward all;
private T Property {get; set;} forward foo1, foo2; reusing keywordsinstead of adding new keywords reusing existing ones might be possible |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
IMO this is something that could be easily achievable with source generators, using custom attributes. It would also allow better tuning of policy, e.g. which methods to be forwarded by default, how to specify allow/blocklists, without requiring a lot of additional syntax to support properly in the language. internal partial sealed class Example {
[Forwarded]
private Test Composited {get; init;} = new();
}
// generated
internal partial sealed class Example {
internal void Try() => Composited.Try();
internal void Force() => Composited.Force();
} |
Beta Was this translation helpful? Give feedback.
-
I finally got to play around with source generators I would really like to see something like this build into .net |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
I finally got to play around with source generators
i created a basic implementation that I'll expand as i need it
https://github.com/BarionLP/Barion.Forwarding
I would really like to see something like this build into .net