Function arguments and object references

G

Guest

Consider the following program:

class MainClass
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
int val = 1;
object o = (object) val;
A a = new A(ref o);
a.ChangeValue(3);
Console.Out.WriteLine("val = {0}", val);
Console.Out.WriteLine("o = {0}", o);
Console.Out.WriteLine("A.Value = {0}", a.RefActualObject);
}
}

class A
{
public object RefActualObject;

public A(ref object other)
{
RefActualObject = other;
}

public void ChangeValue(int val)
{
RefActualObject = val;
}
}

Here's what I was trying to accomplish - pass a reference to the "int val"
variable to the instance of class A (a) so that when the RefActualObject
property of Class A changed, the value of "val" would change. In the example
above, when I called the ChangeValue method on A, the RefActualObject value
changed, but the value of "o" and "val" remain unchanged. I tried "out" but
that didn't work either. Is it possible to do what I am trying to do in C#?
 

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