❔ How to share private variable data between classes when can't inherit?
If I'm supposed to try to encapsulate data as much as possible how can I share data without making everything public if I can't inherit? I'm working on a WPF project right now, but I think this is a problem that would come up in any other time when I can't inherit the data I need (mostly in my experience because I would have to inherit from more than one base class, although maybe there are other times). I keep reading that I should do interfaces to share stuff when I can't inherit, but afaik interfaces only share behavior...not data itself...I can imagine there are ways to share data indirectly through shared behavior but I don't know if I should do it that way or how to do that...
7 Replies
do you have an example case?
you shouldn't use inheritance to share data, inheritance is for subclasses that can be treated the same as the base class
to pull out the corny analogies, you wouldn't derive a Person from a Car just so the Person can see how much gas is in the tank
To continue with the WPF context: if I have a class WindowA, and a class WindowB I can't inherit from one to another (cause they're both already inheriting from Window) and one of the classes needs the value of the other class, how do I access it if I keep that variable private? Again, this is a problem I've had in other non WPF related C# codes so I don't want to get too stuck on the WPF thing
Just how to share private data between different classes through interfaces or any other method?
you just don't make it private
properties are completely valid encapsulation
e.g.
public int MyValue { get; private set; }
that would allow other code to read MyValue but not change itThere's a lot of methods here tbh, as @jimmacle said making it public is one; but there are other scenarios depending on what your needs are.
you also may want to consider if the data even "belongs" to the window
or if you should be extracting it to a shared model
In some cases you can use something like a channel to publish and subscribe
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.