Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Making fields/properties read only conditionally

I have three classes; Classes A and B both reference class C.

How can I make it so members of class C can be modified when referenced from class A but not modified when referenced from class B?

IE, the following should be possible;

classA myClassA = new classA();
myClassA.myClassC.IssueNumber = 3;

But this should not be possible;

classB myClassB = new classB();
myClassB.myClassC.IssueNumber = 3;

Making classB.classC read-only still allows properties of classC to be altered.

I'm sure this is basic stuff but can't find a simple answer.

Thanks, A

like image 766
Alistair77 Avatar asked Apr 08 '10 09:04

Alistair77


1 Answers

Pattern 1: Make a simple read-only interface IRead. Make a simple write interface IWrite. Make an read-write interface IReadWrite : IRead, IWrite. Implement classC : IReadWrite. Declare myClassA.myClassC as IReadWrite. Declare myClassB.myClassC as IRead. (You don't have to user IWrite anywhere if you don't need it :-))

Pattern 2: create a read-only wrapper for classC called ReadOnlyClassC and use that one in classB.

Pattern 1 is used by the IO streams to split the reader and writer implementations and then combine them in read-write streams.

Pattern 2 is used by the generic collections to provide read-only facet.

like image 194
Franci Penov Avatar answered Sep 21 '22 20:09

Franci Penov