Implement Friend Function in C#

  • Thread starter Thread starter Tan
  • Start date Start date
T

Tan

C# does not offer the keyword "Friend" (C++ has it). Is there anyway that I
can emulate this ?

namespace myclass{
public class A
{
protected virtual void Add()
{
}
}

public class B:A
{
private StringCollection MyCollection;

protected virtual void Add()
{
//Add item into MyCollection
}

public StringCollection _MyCollection
{
get { return MyCollection; }
}
}

public class C
{
public DoSomeWorks()
{
B b = new B();
//Call 'friend' functions in B so that B:Add() protection function
get called.
}
}

namespace Test
{
public static void Main(..)
{
C c = new C();

c.DoSomeWorks();
}
}

The idea is to allow C::DoSomeWorks() to call B:Add() protected virtual
function so that data can be added to MyCollection, and thus make
MyCollection remains "readonly" to outsider.

One way is to have class C inherits from class B (something that I am try to
avoid). Can anyone help ? Thanks.
 
Tan said:
C# does not offer the keyword "Friend" (C++ has it). Is there anyway that I
can emulate this ?

The usual solution is to use "internal", which is accessible to the
other classes in the same assembly, but not accessible outside the
assembly.
 
Back
Top