cnharrington
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(obj ect 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
ctrlInt.InitialUpdate(ref gi.m_level);
public void InitialUpdate( ref int Data)
{
mData = Data;
}
private void ControlInt_TextChanged(obj
{
int val = 0;
if (Int32.TryParse(this.Text,
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
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.
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
Thanks
The language itself won't permit such an action:
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:
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.
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:
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.