Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

constructor

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

like image 784
7wp Avatar asked Jan 06 '10 22:01

7wp


2 Answers

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
          }
     }
}
like image 59
Reed Copsey Avatar answered Sep 19 '22 03:09

Reed Copsey


This is how I solved it. I'm not sure if it's the "right" way to do it, but it required minimal effort:

public abstract class X
{
    // "friend" member
    protected X()
    {
    }

    // a bunch of stuff that I didn't feel like shadowing in an interface
}

public class Y
{
    private X _x;

    public Y()
    {
        _x = new ConstructibleX();
    }

    public X GetX()
    {
        return _x;
    }

    private class ConstructibleX : X
    {
        public ConstructibleX()
            : base()
        {}
    }
}
like image 21
hypehuman Avatar answered Sep 18 '22 03:09

hypehuman