The C++ friend keyword allows a
class A to designate
class B as its friend. This allows
Class B to access the
protected members of
I've never read anything as to why this was left out of C# (and VB.NET). Most answers to this earlier StackOverflow question seem to be saying it is a useful part of C++ and there are good reasons to use it. In my experience I'd have to agree.
Another question seems to me to be really asking how to do something similar to
friend in a C# application. While the answers generally revolve around nested classes, it doesn't seem quite as elegant as using the
The original Design Patterns book uses it regularly throughout its examples.
So in summary, why is
friend missing from C#, and what is the "best practice" way (or ways) of simulating it in C#?
(By the way, the
internal keyword is not the same thing, it allows all classes within the entire assembly to access
internal members, while
friend allows you to give a certain class complete access to exactly one other class)
Having friends in programming is more-or-less considered "dirty" and easy to abuse. It breaks the relationships between classes and undermines some fundamental attributes of an OO language.
That being said, it is a nice feature and I've used it plenty of times myself in C++; and would like to use it in C# too. But I bet because of C#'s "pure" OOness (compared to C++'s pseudo OOness) MS decided that because Java has no friend keyword C# shouldn't either (just kidding ;))
On a serious note: internal is not as good as friend but it does get the job done. Remember that it is rare that you will be distributing your code to 3rd party developers not through a DLL; so as long as you and your team know about the internal classes and their use you should be fine.
EDIT Let me clarify how the friend keyword undermines OOP.
Private and protected variables and methods are perhaps one of the most important part of OOP. The idea that objects can hold data or logic that only they can use allows you to write your implementation of functionality independent of your environment - and that your environment cannot alter state information that it is not suited to handle. By using friend you are coupling two classes' implementations together - which is much worse then if you just coupled their interface.
For info, another related-but-not-quite-the-same thing in .NET is
[InternalsVisibleTo], which lets an assembly designate another assembly (such as a unit test assembly) that (effectively) has "internal" access to types/members in the original assembly.