Sharing class member data between sub components

Posted by Tim Gradwell on Stack Overflow See other posts from Stack Overflow or by Tim Gradwell
Published on 2010-06-05T14:03:16Z Indexed on 2010/06/05 15:12 UTC
Read the original article Hit count: 154

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

© Stack Overflow or respective owner

Related posts about .NET

Related posts about object-oriented-design