Alex Rivera | Logout

How to create a constructor that is only usable by a specific class. (C++ Friend equivalent in c#)

Asked 2010-01-06T22:20:10.183
18

As far as I know, in C#, there is no support for the "friend" key word as in C++. Is there an alternative way to design a class that could achieve this same end result without resorting to the un-available "friend" key-word?

For those who don't already know, the Friend key word allows the programmer to specify that a member of class "X" can be accessed and used only by class "Y". But to any other class the member appears private so they cannot be accessed. Class "Y" does not have to inherit from class "X".

Edit
Report

1 Answer

2

What about just having it explicity implement an interface that is only visible to a certain class?

Something like:

public void IFreindOfX.Foo() //This is a method in the class that's a 'friend' to class X.
{
   /* Do Stuff */
}

and then make sure IFriendOfX is visible to class X. In your X class you'd call the method by first casting X to IFriendOfX then calling Foo(). Another advantage is that is is fairly self documenting... that is, it's pretty close to having the friend keyword itself.

answered 2010-01-06T22:29:59.090

Your Answer