Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate C++ friend in C# and VB.NET?

Because sometimes, I really need a friend.

I can think of the following tricks:

  1. Read only wrapper - like ReadOnlyCollection. The friend keeps the pointer to the modifiable object, while everyone else can access only the wrapper.
  2. Write delegate - the friend gives the constructor of the object a reference to a delegate as one of the parameters, the constructor fills it with an address to a private method that can be used to modify the object.
  3. Reflection - obviously a bad idea. Included for completeness.
  4. Multiple assemblies - put your friends together in a separate assembly and set your modifier methods internal.
  5. Expose the modifiable object, but add comments to modifier methods "This is an infrastructure method - don't call it!"
  6. Nested classes.
  7. Add System.ComponentModel.EditorBrowsable(System.ComponentModel. EditorBrowsableState.Never) attribute to the member you want only the friend to access to hide it from IntelliSense.
  8. Implicit interface implementation - see comments.

Is this list exhaustive? Can anyone sort these in order of decreasing performance? Order of decreasing neatness? Any suggestions when to use which?

like image 673
Ansis Māliņš Avatar asked Dec 20 '10 17:12

Ansis Māliņš


2 Answers

You can also use the InternalsVisibleTo attribute.

For a given assembly, A, you can specify which other assemblies can have access to A's internal types.

like image 167
wageoghe Avatar answered Sep 20 '22 14:09

wageoghe


In c# Nested classes (like private classes) are similar to friend in c++:

public class Root
{
   private int a; // accessible for friendroot

   public int b;

   public class FriendOfRoot
   {          
      public int d;
   }

}

Edit: If the simulation of friend with nested classes provided here is useful for you, in performance it's fast enough like regular classes (In compile all things will be determined and there is no casting issues and no overhead).

like image 28
Saeed Amiri Avatar answered Sep 20 '22 14:09

Saeed Amiri