Link to home
Start Free TrialLog in
Avatar of cnharrington
cnharringtonFlag for United States of America

asked on

How do I pass an object.member by reference to a function?

Object gi has an (int) member "level".  ctrInt is a TextBox control with an (int) member "mData".  I would like changes made to the textbox to be stored in gi.level.

        ctrlInt.InitialUpdate(ref gi.m_level);

        public void InitialUpdate( ref int Data)
        {
            mData = Data;
        }
        private void ControlInt_TextChanged(object sender, EventArgs e)
        {
                int val = 0;
                if (Int32.TryParse(this.Text, out val))                 {
                    if (!((m_min <= val) && (val <= m_max)))
                    {
                          errMsg = "Please enter an integer between " + m_min + " and " + m_max;
                    }
                    else
                    {
                        mData = val;  // updating mData does not also update also update gi.level
                    }
        }

Is it possible to store the reference to an object member within a function as shown above?

Thanks,

Craig Harrington
Avatar of kaufmed
kaufmed
Flag of United States of America image

No, not with value-type properties. You would have to pass the class/struct itself into the method in order for it to be updated from within the function.
Avatar of cnharrington

ASKER

I am concluding that there is no way the determine the "reference" address for the object.member and only the address of the object itself can be passed as an "ref" argument.  I have solved the problem by adding a delegate which provides the member updating functionality.

Thanks
The language itself won't permit such an action:

User generated image
 The closest you could get would be to declare a variable outside of the method, pass that in, and then reassign the value after the function executes:

User generated image
The reason why you cannot do what you are trying to achieve is because properties in .NET are compiled to methods behind the scenes, and you cannot pass a method by reference. Properties are merely a convenience to handling data access in .NET. At the end of the day, they are just methods.
ASKER CERTIFIED SOLUTION
Avatar of cnharrington
cnharrington
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial