Click to See Complete Forum and Search --> : Question about references


gbr
July 23rd, 2005, 10:00 AM
Hi,

I'd like to devide my data from the user interface. Hence, I passe a reference from my data to each control. In theory, if I change the data and redraw the control, it should be able to access the data (because there are no copies of this data variable) and redraw according to the data value.

In order to ******** my description I will go into details: The control which is added to the main form is a derived Panel, which has a data variable which contains the color of this Panel. The data is stored in a Color array and passed to the constructor of the panel


for( int i=0; i < color.Length; i++ )
{
ColorPanel pan = new ColorPanel( ref colors[i] )
this.Controls.Add( pan );
}


However the theory is not matching the practise. If I change one item of the colors array and redraw the main form, the color of the colorpanel is not changed. Of course, I overwrote the ColorPanel OnPaint method to set the particular background color. The trace output showed that the old color value is still existing...

So, how to pass a reference packed in an array in c#?

Thanks,
gbr

deesan
July 23rd, 2005, 12:30 PM
Color is a struct, not a class. All structs are value types (like int, string etc), so when you assign one variable of struct type to another, all fields of first will be copied to appropriate fields of second.

If you do assignment with class variables then second variable will refer to the same object in memory as first.


Try to use some wrapper for panel-specific data. For example:


class PanelData
{
public Color color;
public PanelData(Color aColor)
{
color = aColor;
}
}

gbr
July 23rd, 2005, 02:11 PM
Okay, that worked, thank you.