Using friend with C#

  • Thread starter Thread starter Mike Peretz
  • Start date Start date
To grant member-level access to functions that are not members of a
class or to all functions in a separate class, C++ has a mechanism to
use friends.

However this violates the rules of basic Object Oriented world!!! So
C# does not allow friends. (To the best of my knowledge)

-Cnu
 
To grant member-level access to functions that are not members of a
class or to all functions in a separate class, C++ has a mechanism to
use friends.

However this violates the rules of basic Object Oriented world!!! So
C# does not allow friends. (To the best of my knowledge)

It doesn't have friend access in the same way as C++, but there is the
concept of a "friend assembly" using InternalsVisibleToAttribute. That
allows one assembly to access the internal members (not private - just
internal) of another. I've found it useful in unit testing, but not
elsewhere.

Jon
 
Duggi said:
To grant member-level access to functions that are not members of a
class or to all functions in a separate class, C++ has a mechanism to
use friends.

However this violates the rules of basic Object Oriented world!!! So
C# does not allow friends. (To the best of my knowledge)

I tend to disagree.

Encapsulation is a core aspect of OO.

But it is not obvious to me that friend is violating that.

You can grant access to everyone via public or sub classes
via protected or in C# to the assembly via internal. In C++
you can grant access to a specific class or specific method.

That is a finer granularity of control than C#. But that is
not less encapsulation. It could be argued to be more
encapsulation.

As with so many C++ constructs then it require a wise man
to decide when to use them - misuse is rather easy. So I
find it understandable that C# omitted that feature. The
benefit/complexity ratio is too small.

As has already been mentioned then C# do have a feature with
the same concept: InternalsVisibleToAttribute.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top