Background: I have enclosed (parent) class E with nested class N with several instances of N in E. In the enclosed (parent) class I am doing some calculations and I am setting the values for each instance of nested class. Something like this:
n1.field1 = ...;
n1.field2 = ...;
n1.field3 = ...;
n2.field1 = ...;
...
It is one big eval method (in parent class). My intention is — since all calculations are in parent class (they cannot be done per nested instance because it would make code more complicated) — make the setters only available to parent class and getters public.
And now there is a problem:
- when I make the setters private, parent class cannot acces them
- when I make them public, everybody can change the values
- and C# does not have friend concept
- I cannot pass values in constructor because lazy evaluation mechanism is used (so the instances have to be created when referencing them — I create all objects and the calculation is triggered on demand)
I am stuck — how to do this (limit access up to parent class, no more, no less)?
I suspect I’ll get answer-question first — “but why you don’t split the evaluation per each field” — so I answer this by example: how do you calculate min and max value of a collection? In a fast way? The answer is — in one pass. This is why I have one eval function which does calculations and sets all fields at once.
If it’s possible for you to put the parent and child classes in another assembly, you can make use of
internalfor the setters. That’s generally how this is dealt with in the wild.EDIT:
Thomas Levesque’s answer gave me an idea:
Depending on how you need to expose the child class
N, this could work.