Create a new object in a method and pass it back by ref

  • Thread starter Thread starter Allan Lembo
  • Start date Start date
A

Allan Lembo

Hi Folks

If I create a new instance of an object within a method how can I pass
it back by reference?

For example, the following code, in the context of an ASP.NET page,
returns "Original Label". Why not "New Label"? I realise I could give
CreateSomething a return type of Label and return it that way but in
my case I have more than one parameter that could need reinstancing.

Thanks, Al.


private void Page_Load(object sender, System.EventArgs e)
{
Label l;
l = new Label();
l.Text="Original label";
CreateSomething(l);
Response.Write(l.Text);
}

private void CreateSomething(Label l)
{
l = new Label();
l.Text="New Label";
}
 
Allan Lembo said:
If I create a new instance of an object within a method how can I pass
it back by reference?

You need to pass the parameter by reference to start with.
For example, the following code, in the context of an ASP.NET page,
returns "Original Label". Why not "New Label"?

Because the value of l in Page_Load (which is a reference) has been
passed by value. Changing the value of l in CreateSomething doesn't
change the value of l in Page_Load. Note that I'm being precise here -
if you change something within the object that l refers to, that change
will be visible through l, because the value of l *itself* has not
changed.
I realise I could give
CreateSomething a return type of Label and return it that way but in
my case I have more than one parameter that could need reinstancing.

See http://www.pobox.com/csharp/parameters.html for more information
about this.
 
Hi Allan,

You are passing the parameter as value that's why it's not changed back in
the code, you could either pass it as ref or use instead the return value
for doing this:
private void Page_Load(object sender, System.EventArgs e)
{
Label l;
l = new Label();
l.Text="Original label";
l = CreateSomething();
Response.Write(l.Text);
}

private Label CreateSomething()
{
l = new Label();
l.Text="New Label";
return l;
}


What are you trying to do anyway?

Remember that the old l will only cease of exist if there are not any other
variable referencing it. ( as in the example above) .

Cheers,
 
Jon Skeet, Ignacio Machin

Thank you for your replies gentlemen. Now I see. I thought that
because it was an object it was automatically passed as a reference,
whereas actually what's happening is an object reference is being
passed by value. Which is different!

Thanks again, Al.
 
Back
Top