Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Class Conundrum

Tags:

c#

.net

oop

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.

like image 331
Tony D Avatar asked Mar 01 '23 06:03

Tony D


1 Answers

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.

like image 74
Asaph Avatar answered Mar 12 '23 18:03

Asaph