The C++ friend keyword allows a class A
to designate class B
as its friend. This allows Class B
to access the private
/protected
members of class A
.
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 friend
keyword.
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)
On a side note. Using friend is not about violating the encapsulation, but on the contrary it's about enforcing it. Like accessors+mutators, operators overloading, public inheritance, downcasting, etc., it's often misused, but it does not mean the keyword has no, or worse, a bad purpose.
See Konrad Rudolph's message in the other thread, or if you prefer see the relevant entry in the C++ FAQ.