views:

136

answers:

9

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".

+3  A: 

No, there is no way to do that in C#.

One common workaround is to based the object for which you want to hide the constructor on an interface. You can then use the other object to construct a private, nested class implementing that interface, and return it via a Factory. This prevents the outside world from constructing your object directly, since they only ever see and interact with the interface.

public interface IMyObject
{
     void DoSomething();
}

public class MyFriendClass
{
     IMyObject GetObject() { return new MyObject(); }

     class MyObject : IMyObject
     {
          public void DoSomething() { // ... Do something here
          }
     }
}
Reed Copsey
This actually seems to work quite well for my purposes. I have to compromise a bit on the placement of the objects, and name space... but it does achieve what I want to do, +1
Roberto Sebestyen
Well, the interface can be in a different namespace, so there shouldn't be any compromises there. Placement of objects (in code) unfortunately does change, following this pattern.
Reed Copsey
+1  A: 

No. The closest you have is an internal constructor, or a private constructor and a separate factory method (probably internal, so you haven't saved much).

Marc Gravell
+1  A: 

As far as I know, the Internal keyword is the closest thing in .NET. This question will shed more light on Internal: Internal in C#

John Kraft
+2  A: 

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.

Rodrick Chapman
This only applies to objects and won't work for constructors but I honestly can't see why you would need to do that unless what you're saying is that the there are only some states in which the object is valid when it is being used by the friend. In that case you really want to derive a new 'Friendly' class from the class in question that is only visible to the 'Friend' class.
Rodrick Chapman
+1  A: 

As a workaround, I suppose you could create a conditional in your constructor that uses reflection.

For example, if Class1's constructor must be called by Class2:

public Class1()
{
    string callingClass = new StackFrame(1).GetMethod().DeclaringType.Name;

    if (callingClass != "Class2")
    {
        throw new ApplicationException(
            string.Concat("Class1 constructor can not be called by ",
            callingClass, "."));
    }
}

EDIT:

Please note that I would never actually do this in "real" code. Technically it works, but it's pretty nasty. I just thought it was creative. :)

Andy West
A: 

You can access private members/methods using Reflection.

Since it's got the design tag, I never particularly liked the friend keyword. It pierces encapsulation and that always felt dirty to me.

48klocs
A: 

This has a bit of a smell. There are other plenty of other ways to achieve implementation hiding in C#. Limiting construction to only specific classes does not achieve all that much.

Could you please provide more information as to the purpose of this requirement? As already answered, internal is the closest match for limiting accessibility to the class. There are ways to build on top of that depending on the purpose.

Igor Zevaka
+1  A: 

The only thing I can think of that would even come close would be protected internal but that does not restrict it to a specific class. The only friending I'm aware of in c# is to make a friend assembly. Still does not restrict to a specific class.

The only thing I could think of to try and do it would be to do something like the following:

public class A
{
   public A() {}
   protected internal A(B b) {}
}

public class B
{
   A myVersion;

   public B() 
   {
      myVersion = A(this);
   }
}

The only other way I could think of would be to do some sort of Constructor Injection using reflection that is done inside of your friend class. The injection mechanism would allow you to limit it to what you want but could be very cumbersome. Take a look at something like Spring.Net for some injection capabilities.

Joshua Cauble
Remember that "protected internal" means the *more permissive* combination of protected and internal, not the *less permissive* combination.
Eric Lippert
+1  A: 

What about creating a private class? This does exactly what you seem to be describing. A member of class X can be accessed and used only by class Y, and to any other class it appears private, since, well, it is private:

public class Y
{
   private class X { }

   private X Friend;

   public Y()
   {
      Friend = new X();
   }
}
Robert Rossney
I was hoping to define the friend class in a different assembly. However is it possible to tell the private class to be in a different namespace?
Roberto Sebestyen