[Proposal]: [Friend Classes Sugar via Partial Nested Classes] #8830
Unanswered
Austin-bryan
asked this question in
Language Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Friend Classes Sugar via Partial Nested Classes
Summary
When we use the contextual keyword
friend
followed by the class it's friends with, the compiler will automatically convert it to a nested partial class to that friend class. It does so because that's the closest we can get to a friend class using the CLR. This just provides a much shorter way of typing it.Motivation
I've heard that C# can't have friend classes because the CLR does not support it and the closest it has is Internal which isn't close and could cause other issues. So, us as devs, have to use nested partial classes and that's the best we get, which, to be fair, is pretty good, but it's a lot of boilerplate code. This solution is about using a friend keyword to automatically convert the code to a partial nested class, in the manner we normally do it.
Detailed design
Suppose we had the following:
Since CLR doesn't support friend classes, the best way of having only one class be able to modify the value of
x
is this:This is fine but it takes much longer to type, and either makes the
Foo
class very long or involves partial classes and uses up an indentation space which limits realestate for other code. Also, if we wantedFriend
to be public as well it now has to be accessed withFoo.Friend
which is another minor inconvenience.This friend keyword will then turn the Friend class into a nested partial class by the compiler so its much faster to type. Another feature could be is that it would turn
Friend
calls intoFoo.Friend
when it needs to, throwing errors when they're ambiguity, basically just like a using statement. This should allow us to use what feels like a friend class, while the compiler treats it like a nested class.Drawbacks
It's mostly syntatic sugar so it's not too important.
Alternatives
The main alternative is the nested partial class method, but as mentioned, it's much longer to type, takes up more indents and forces a longer class name for the nested class.
Unresolved questions
Not sure if friend classes should be implicitly public to outside of the class, or what it would mean to use the private keyword, seeing as it's a nested class under the hood, but if it was designed such that only the
Foo
class could see it when it's private, that would feel jarring and unexpected.Beta Was this translation helpful? Give feedback.
All reactions