views:

179

answers:

4

Ok, let's leave the debate of whether friendship breaks encapsulation, and actually try elegantly come up with a coherent design. It is a two fold function:

1) General question on how to implement:

  public class A 
   {
      friend class B;
   }

2) Why do I need this functionality? Some of my classes implement ISerializable interface. However, I want to make ISerializable methods protected in the Derived class so that I don't expose them to aclient (as well as in the documentation). However, internal classes should be able to access them. What is the General way to solve this problem in C#?

Note: I am using friendship as defined in the current C++ standard.

Thanks

+4  A: 

C# has the internal keyword, so that other types in the same assembly see the types marked internal. Additionally, you can add attributes to the assembly to allow types outside of the assembly to see that assembly's internal members.

Joel Coehoorn
please provide an example of that. The goal of the design is to make sure that CLIENT knows nothing of the existence of this method.
The client can always use reflection to discover any methods.
Ben S
A: 

internal members are public within the current .dll and private externally. Additionally, you can expose them to external .dll's by using the InternalsVisibleTo attribute.

Timothy Carter
+4  A: 

If the classes are in the same assembly you can use internal. If they're in different assemblies you can use the friend assembly attribute.

Ben S
this is good! thanks...
+1  A: 

Leaving the InternalsVisibleTo stuff to one side, you only have two choices when it comes to implementing interfaces:

  • Implement them with public methods
  • Implement them using explicit interface implementation

In both cases anyone can call the methods, but using explicit interface implementation you can only call the methods "via" an interface expression (e.g. you could cast a variable of the actual type to the ISerializable).

There's no such concept as "internally" implementing an interface.

Jon Skeet
These were my thoughts to... but for the sake of argument, what happens if you try to mark an interface implementation method as internal?
Matthew Scharley
It will no longer implement the interface and you'll get a compile-time error. Not sure why my answer got downvoted though, given that it's actually addressing the question...
Jon Skeet
Jon, you solved first part of the question -- this will in fact, prevent a client from calling the method. The second part: I want this method to NOT be public, else doxygen will export it to documentation, thus confusing users of the API. I gave you an up-vote