[C# Feature Request] Type embedding #8433
Unanswered
gosub-com
asked this question in
Language Ideas
Replies: 1 comment
-
You could use a source generator to emit the forwarding calls.... |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
If I want my class to provide features from another class, I can either:
None of these options are ideal, so I'd like to have something similar to type embedding from Golang https://go.dev/doc/effective_go#embedding, which allows an automatic version of method #2 above.
For example, if we have some classes we want to use functionality from:
Using method #3 above, I can add that functionality to my class:
But I'd prefer users of my class to not need to deal with
Stuff1
orStuff2
, and I'd likeA
andB
to serialize at the same level asC
.This example uses a non-existent syntax with the
using
keyword to show what type embedding might look like in C#:There have been some complaints about type embedding. One complaint is it looks like inheritance, but acts differently. Another is that adding new features to the embedded type may add unwanted new features to the class using them. To address those complaints, I propose requiring explicit annotations on which functions and properties are publicly visible:
The list of symbols
[A, DoSomething]
makes it clear that only those symbols are being publicly exported and also protects from having new fields or functions appear magically when something was added to the embedded type. Note that the list of symbols includes all overloads with the same name (e.g. Addingvoid DoSomething(int a)
toCommon1
adds the new overload toUseCommon
).The special syntax
using Common3[*]
could be used to allow exporting all public members. There may be cases where we want to allow users of our class to access the embedded class directly, in which casepublic using Common3[*]
could be used to allow public access toCommon3
(as a readonly field or property). Neither of these uses can be confused with inheritance since there is no implicit conversion to the embedded type.I also propose that this syntax automatically create a new readonly class during construction, and by extension require that the embedded class have an empty constructor. Internally,
using Common1[...]
would translate to something likereadonly Common1 Common1 = new();
This allows a simpler syntax, easier deserialization, and embedded types are always known to be non-nullable.Beta Was this translation helpful? Give feedback.
All reactions