1

I have an issue with accessibility of class members.

I have 3 classes that work together and need full access to each others properties. classA, classB, classC

However classA is uses somewhere else and all users of that class should only have read access to all structures!!

The classes look like this:

public class classA
{
    public ClassB B { get ; }
    ...
}

public class classB
{
    ClassC C { get ;  set ; }
    ...
}

public class classC
{
    ArrayList L { get ;  set ; }
    ...
}

How can I manage that classA and classB have full access on classC, but all users of class A cannot modify anything inside?

For example this is still possible :(

classA A = new A();
A.B.C.L.Add( something);

even if A.B cannot be modified due to the missing set.

One possibility I see is, that property A.B returns a deep-copy of the structure, so that modifying A.B does not affect the source structure, but I'm not really satisfied with that.

Is there a way that write access is checked at compile time as if I used 'readonly' or omit a 'set;'?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
CSharper
  • 298
  • 2
  • 13
  • 1
    Check http://stackoverflow.com/questions/204739/what-is-the-c-sharp-equivalent-of-friend – devshorts Apr 07 '13 at 13:50
  • 2
    If you expose something like ArrayList / List-of-T, then it is already "game over". You would have to expose an outwardly immutable list. Are those classes in a separate assembly? If so, "internal" may help. There is no "friend" level access in c# – Marc Gravell Apr 07 '13 at 13:59

1 Answers1

2

The easiest approach is to provide a read only proxy for accessing the data in B - just like the ReadOnlyCollection, which wraps a regular collection, providing a read only version of the same interface. So you wouldn't return a classB, but a ReadOnlyB.

Alternatively this read only interface could be implemented in classA to allow more "direct" access to the data.

You could possibly then put A,B,C into a different assembly and make B,C internal so that the client can't see them.

Jason Williams
  • 56,972
  • 11
  • 108
  • 137