tags:

views:

54

answers:

2

Hi everyone. Please help me out here because im getting kind of confused.. I have a form in a C# winforms project and a couple of methods that are suposed to perform some tasks for this particular form and all derived ones, so one of those helper methods can make the example.. this one should fill comboboxes with a dataset. Its working properly now but when i coded the method with this signature

protected void FillComboBox(kComboBox target, IEntClass_DA entity)
        {
            target.DataSource = entity.GetList().Tables[0];
            target.DisplayMember = "name";
            target.ValueMember = "id";
        }

I saw that the displayMember and ValueMember in the comboboxes were not holding the values after the method call. I just thought I should use ref parameters so the asignments are not wasted in read-only reference variables.

It was ok by then but later, making an exercise of passing the whole form as a parameter I was warned by the compiler with the notice that this could not be passed as a ref parameter because it is read-only. Fine then, I keep working and see that even without the ref keyword i can use the ref variable from the form, update some properties and see the changes.

So whats happening here: passing a reference of the control to the helper method gives me ability to change its members even when not using the ref parameter??

Thanks.

+6  A: 

Your last statement is absolutely correct. You're passing a reference to the control; you can change the contents of that control via the reference, but if you change the value of the parameter to refer to a different control entirely, that change wouldn't be propagated to the calling code.

See my article on parameter passing for more details of this commonly-misunderstood area.

Jon Skeet
+2  A: 

You are passing a reference type, so there should be the same result whether you use ref or not...

Machta