tags:

views:

23

answers:

1

I have an aggregate 'main' class which contains some data which I wish to share. The main class also has other class members. I want to share the data with these other class members. What is the correct / neatest way to do this?


The specific example I have is as follows. The main class is a .net Form. I have some controls (actually controls within controls) on the main form which need access to the shared data.

Main Form
- DataX
- DataY
- Control1
-- Subcontrol1
- Control2
-- SubControl2

SubControls 1 and 2 both wish to access DataX and DataY.

The trouble is, I feel like better practice (to reduce coupling), would be that either subcontrols should not know about Main Form, or Main Form should not know about subcontrols - probably the former.

For subcontrols not to know about Main Form, would probably mean Main Form passing references to both Controls 1 and 2, which in turn would pass the references on to SubControls 1 and 2. Lots of lines of code which just forward the references. If I later added DataZ and DataW, and Controls 3 and 4 and SubControls 3 and 4, I'd have to add lots more reference forwarding code.

It seems simpler to me to give SubControls 1 and 2 member references to Main Form. That way, any sub control could just ask for MainForm.DataX or MainForm.DataY and if I ever added new data, I could just access it directly from the sub controls with no hassle. But it still involves setting the 'MainForm' member references every time I add a new Control or Subcontrol. And it gives me a gut feeling of 'wrong'.

As you might be able to tell I'm not happy with either of my solutions. Is there a better way?

Thanks

+1  A: 

you could make data x and data y static members so you can access them this works fine if you just have one instance of the main form running

Patrick Säuerl
I do have more than one instance of the main form, so static isn't an option for me in this case.
Tim Gradwell
To avoid making new implementations for every new Data you have you can put it all into an array or list so the controls just need access to this arrayHave the subcontrols knowledge about the higher controls ?
Patrick Säuerl
yes, but I'd rather they didn't. I suppose I could just package up the data in a container (possibly the array that you suggest). Thanks.
Tim Gradwell