Reputation: 1531
For simplicity let's say I have two classes: a class called Car and a collection class called Tires. Tires is a nested class inside the Car class. I want to give my clients access to the collection - i.e. they should be able to iterate over it:
foreach( var tire in car.tires ) ...
and access each tire's properties. But I don't want to give them access to the methods in tires. I want all access to behavior to come through the Car class:
car.FillTires();
Scenario 1: Tires class is public with methods private: Car class can't access Tire methods.
Scenario 2: Tires class is private with methods public: I can't expose the collection to my clients.
Internal doesn't work for me either as I don't want to grant other classes in the assembly access.
Upvotes: 4
Views: 210
Reputation: 14746
A simple solution is to re-evaluate if Tires
should be an inner class. If you make it a normal class you can simply use internal
and public
to differentiate between what clients and what Car
can access.
If there is an unrelated reason why Tires
should be an inner class, expose only a read-only version:
Car
with a new one every time you want to change something.)Car
complete control while limiting public access without any inconvenience or copying.Upvotes: 3
Reputation: 23138
You may write class FakeTire that extends Tire.
Override FillTires to throw an exception in FakeTire class. Car has a list of real tires, but it's Tires property creates a list of Faketires to give out. Kindof like a read only collection.
Upvotes: 0
Reputation: 18118
Option 1: You could put Car in a separate assembly and use scenario 1ish (Tire could be public + methods internal).
Option 2: You could make Tire immutable (like String) and let consumers do what ever they want with tires, but they can not change the tires within the car (make the tires collection's property readonly but do not make the private backing field readonly).
Upvotes: 2
Reputation: 162851
Create an interface with only the methods you wish to clients to access and expose a collection of the interface type through your class's methods.
Upvotes: 3