reference type parameter and property

J

jbaldi

I am trying to pass an object as a reference parameter in a
constructor. I would like my class with the reference parameter
constructor to be able to change the value of that object from one of
its methods as in the following example.

public class Class1 {

private object _myObject;

public Class1(ref object myObject) {

_myObject = myObject;

}

public void ChangeValue( ) {

_myObject = 1;

}


}

public class Class2 {

public Class2( ) {

object myObject = 0;

Class1 myClass1 = new Class1(ref myObject);
myClass1.ChangeValue( );

object foo = myObject;

}

}

My problem is that foo will have a value of 0 instead of 1. I thought
that objects were reference types so this should work. What am I
missing?
 
J

Jon Skeet [C# MVP]

I am trying to pass an object as a reference parameter in a
constructor. I would like my class with the reference parameter
constructor to be able to change the value of that object from one of
its methods as in the following example.

My problem is that foo will have a value of 0 instead of 1. I thought
that objects were reference types so this should work. What am I
missing?

You haven't fully understood reference types and reference parameters.

Hopefully the following might help. The second one is very much a work
in progress:

http://pobox.com/~skeet/csharp/parameters.html
http://pobox.com/~skeet/csharp/references.html
 
J

Jon Skeet [C# MVP]

I still don't see how would I get ChangeValue( ) to make foo = 1. If
I set myObject to 1 in Class1's constructor then foo should be 1 but I
don't see a way to do it using the _myObject.

You can't, basically. You *could* create an ObjectWrapper class like
this:

public class ObjectWrapper
{
object value;

public object Value
{
get { return value; }
set { this.value = value; }
}
}

You could change the constructor to take an ObjectWrapper, store that,
and then change the contents at a later date.

It would rarely be a good design decision, however. Now, what higher
goal are you trying to achieve?
 

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