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

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
          }
     }
}

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()
        {}
    }
}

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

Tags:

C#

Constructor