How to handle

  • Thread starter Thread starter windsurfing_stew
  • Start date Start date
W

windsurfing_stew

Consider the following code:

public void MyMethod(Object myObject)
{
myObject = anotherObject;
}

After this method is called myObject will still contain a reference to
it's original object rather than anotherObject. Eg,

MyMethod(myObject);
MessageBox.Show(myObject.GetType.ToString());

My question is, how can I change the parameter descriptions on MyMethod
so that myObject references anotherObject after it is called?

Hope you can assist,

Stewart
 
Hi,

Use:
public void MyMethod(ref Object myObject)
or
public void MyMethod(out Object myObject)
 
Consider the following code:

public void MyMethod(Object myObject)
{
myObject = anotherObject;
}

After this method is called myObject will still contain a reference to
it's original object rather than anotherObject. Eg,

MyMethod(myObject);
MessageBox.Show(myObject.GetType.ToString());

My question is, how can I change the parameter descriptions on MyMethod
so that myObject references anotherObject after it is called?

You need to pass the parameter by reference.

See http://www.pobox.com/~skeet/csharp/parameters.html

Personally I would try to avoid such code where possible though, using
return values in preference.
 
Hi Jon,

This link is excellent. I found it much more informative than
Microsoft's description. In fact the Framework help for ref and out
are really poor and really only cover value types.

I'm reasonably new to C# after 5 years of VB.Net so the out is new to
me!

Many thanks!

Stewart
 
Back
Top