Search code examples
c#oopfriend

C# equivalent to C++ friend keyword?


I am new to C#, and I have a problem for which in C++ I would normally use the friend identifier. Now I know the friend keyword doesn't exist in C#, but I don't have any experience with how to work around this (except for making all class variables public properties, which I want to avoid if I can).

I have the following scenario:

public class A 
{
    public string Info { get; set; }
    /* much more data */
}

public class B
{
    private A m_instanceOfA;

    public B(A a) { m_instanceOfA = a; }

    public Info { get return A.info; set A.Info  = value; }

    /* And some more data of its own*/
}

public class C
{
    private A m_instanceOfA;

    // I need a constructor of C, which needs to set C.m_instanceOfA
    // to the same value as b.m_instanceOfA.
    public C(B b) { m_instanceOfA = b.m_instanceOfA ; } // <--- Not allowed!

    /* And some more data of its own*/
}

Is there any other clever way, without making B.m_instanceOfA public, to give C access to this variable (only in the constructor)?


Solution

  • Internal

    You can use the internal keyword. Your type (or type member) will then only be visible to other types within the same assembly; And also:

    If you need your internal types to be visible from other assemblies, you can use the InternalsVisibleToAttribute. This attribute targets your whole assembly and is usually written in the AssemblyInfo.cs file.


    PS: Friend keyword doesn't exists in C# but the concept of friendship exists (not exactly the same as the one in C++), it is described on the Friend Assemblies article from the MSDN. Note also that a friend keyword exists in VB.NET and has the exact same behaviour than the C# internal keyword.