How to handle

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
 
A

Alex Koltun

Hi,

Use:
public void MyMethod(ref Object myObject)
or
public void MyMethod(out Object myObject)
 
J

Jon Skeet [C# MVP]

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.
 
W

windsurfing_stew

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top