Ref Propogation in C#

O

Ori

Hi,

I have a simple question.

Let say that i have 3 functions as following

private main()
{
Object oTop = new Object();
}

private void A(ref Object obj)
{
B(obj)
}

private void B(Object obj)
{
obj = "1";
}

Does the function B receive the same reference to the object "oTop"
(as A) or it receive a copy of the reference?

What is the best way to keep using the same reference between those
functions? Do i need to add a ref to the B function and make it like
this:
private void B(ref Object obj)
{
obj = "1";
}

Please help me in this point. I'm looking to find the most efficient
why to keep with the reference propogation ( i need a reference
because i update the object).

Thanks.
 
J

Jon Skeet [C# MVP]

Ori said:
I have a simple question.

Let say that i have 3 functions as following

private main()
{
Object oTop = new Object();
}

private void A(ref Object obj)
{
B(obj)
}

private void B(Object obj)
{
obj = "1";
}

Does the function B receive the same reference to the object "oTop"
(as A) or it receive a copy of the reference?

It receives a copy of the reference. That is also "the same reference",
but the formal parameter in B doesn't have the same memory location as
the formal parameter in A.
What is the best way to keep using the same reference between those
functions?

You need to get your terminology correct here, otherwise it'll be very
difficult to understand what you're actually doing.
Do i need to add a ref to the B function and make it like
this:
private void B(ref Object obj)
{
obj = "1";
}

You *could* do that, although in the above it would be better just to
make your method return a string.
Please help me in this point. I'm looking to find the most efficient
why to keep with the reference propogation ( i need a reference
because i update the object).

If you're updating the object rather than creating a new object, you
don't need to pass by reference in the first place.

See http://www.pobox.com/~skeet/csharp/parameters.html for more
information.
 
O

Ori Anavim

The function which i put were only for example and not for something
real.

I just was interesting for the general concept .

As I wrote, I would like to understand what is the best way to pass
reference between functions and when exactly we need to use the "ref"
keyword.

I want to know whether we need to use the "ref" with every function
which going to receive the object or it's enough to do it only once (in
the first function which pass this parameter).

Thanks.
 
J

Jon Skeet [C# MVP]

Ori Anavim said:
The function which i put were only for example and not for something
real.

I just was interesting for the general concept .

As I wrote, I would like to understand what is the best way to pass
reference between functions and when exactly we need to use the "ref"
keyword.

I want to know whether we need to use the "ref" with every function
which going to receive the object or it's enough to do it only once (in
the first function which pass this parameter).

Did you read the page I gave the link for? That should explain
everything better than I have time to at the moment.
 
O

Ori Anavim

Yes, i've read the article , but it doesn't answer to my question.
I will try to explain my self in a different way:

Let say that i have the following function:

void Foo()
{
MyObject m = new MyObject();
MyFunctionA(ref m);
}

In this case we send a refrence to the m object which we create in the
Foo function (so far its trivial).
Now lets see how the MyFunctionA (and MyFunctionB) are look like:

void MyFunctionA(ref MyObject obj)
{
MyFunctionB(m);
}

void MyFunctionB(MyObject obj)
{
//change the content of obj
}

Here is my question:

Doing so, I’m calling the function MyFunctionB with the reference of
MyObject which I create in the Foo function. Do I need to use the
keyword ref in the MyFunctionB
In order to send the MyObject instance byRef or because I already did it
(when I call to MyFunctionA) I don’t need to do it again?

Does it matter in this case? Is there is any difference if I would
change MyFunctionB to be as following
void MyFunctionB(ref MyObject obj)
{
//change the content of obj
}

and when I will call it from MyFunctionA I will use is as following:

void MyFunctionA(ref MyObject obj)
{
MyFunctionB(ref m);
}

To make things clear, I’m not a C# beginner, but a very experience one,
nevertheless, last night I try to figure out whether we send a ref
“byRef” make any difference in the memory usage (different address or
not?) and in the performance issues

Thanks again,

Ori.
 
B

Bruno Jouhier [MVP]

If you just want to pass the same object (I am not talking about structs),
to different methods, you don't need the ref keyword. By default (without
ref), you are passing the reference around.

On objects, the ref keyword is only useful in the rare cases where you want
the method to return a different object through the parameter.

So, don't put ref keywords everywhere, it will mislead those who use your
methods into thinking that your method "returns" something through these
parameters.

Bruno.
 
J

Jon Skeet [C# MVP]

Ori Anavim said:
Yes, i've read the article , but it doesn't answer to my question.

I really think it does - you just need to be very careful about your
terminology. You talk about passing an instance by reference - you
never pass an instance of a reference type either by value *or* by
reference - you pass a *reference* to an instance by reference or by
value.
I will try to explain my self in a different way:

Let say that i have the following function:

void Foo()
{
MyObject m = new MyObject();
MyFunctionA(ref m);
}

In this case we send a refrence to the m object which we create in the
Foo function (so far its trivial).

Be clear in your terminology here - there is no "m object". There is
the object that the value of m is a reference to. That object isn't
passed and can't be. The variable m may be passed by reference, or the
value of m may be passed by value. Note that just to change data
*within* that object, however, you don't need to pass anything by
reference.
Now lets see how the MyFunctionA (and MyFunctionB) are look like:

void MyFunctionA(ref MyObject obj)
{
MyFunctionB(m);
}

void MyFunctionB(MyObject obj)
{
//change the content of obj
}

Change the content of the object that the value of obj is a reference
to, or change the value of obj to be a reference to another object?

If it's the former, you don't need to have used "ref" anywhere. If it's
the latter, you need "ref" in the declaration of the parameter to
MyFunctionB as well.
 
J

Jeff Louie

Use the ref keyword when you want to add another level of indirection.
You
can achieve the same effect by packing an object into a wrapper class.

5) Values and References to Objects are Passed By Value

By default, objects in C# are not passed by reference. (Unlike Java, C#
does
support passing by reference using the ref keyword.) In C#, you pass a
reference or a value to a method. You cannot pass an object to a method.
By
default, all calls to methods are by value. Now is that clear! In other
words,
you pass a reference to an object to a method, not the object itself.
The
reference is passed by value so that the a copy of the reference goes on
the
stack. The key here is that the object is not copied onto the stack and
you can
touch the object while inside the method. If you want to truly pass an
object
by reference (for a swap routine) use the ref keyword. Remember, you
cannot
pass an object, so you are actually passing a reference by reference.
Oh, I
have a headache.

Note: This topic has been a source of great confusion to C++ coders, so
I will
elaborate. If you want to write a swap routine then you need to add
another
degree of indirection to the method call. You can do this by use the
keyword
ref. Here is some sample code that demonstrates the concept. The swap
routine only works if you pass a reference to a concrete Drawable object
by
reference.

using System;

namespace TestSwap
{
abstract class Drawable
{
abstract public void DrawMe();
}
class Circle : Drawable
{
public override void DrawMe()
{
System.Console.WriteLine("Circle");
}
}
class Square : Drawable
{
public override void DrawMe()
{
System.Console.WriteLine("Square");
}
}
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static public void SwapByValue(Drawable d1, Drawable d2)
{
Drawable temp= d1;
d1 = d2;
d2= temp;
}
static public void SwapByRef(ref Drawable d1, ref
Drawable d2)
{
Drawable temp= d1;
d1 = d2;
d2= temp;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Drawable wasCircle= new Circle();
Drawable wasSquare= new Square();
wasCircle.DrawMe(); // outputs Circle
wasSquare.DrawMe(); // outputs Square
SwapByValue(wasCircle, wasSquare); // fails
wasCircle.DrawMe(); // outputs Circle
wasSquare.DrawMe(); // outputs Square
SwapByRef(ref wasCircle, ref wasSquare); //
succeeds
wasCircle.DrawMe(); // outputs Square
wasSquare.DrawMe(); // outputs Circle
System.Console.ReadLine();
}
}
}


You can mimic pass by reference in Java by "packing" the concrete
Drawable
object into a wrapper class. You can then pass a reference to the
packing
object to a swap routine by value. This added level of indirection
allows you
to implement a swap routine, so that you can swap the concrete Drawable
object in each packing object.

Regards,
Jeff
 
B

Bruno Jouhier [MVP]

Hi Jeff,

In Java, you can also pass an array of 1 element when you want the method to
return a result through the argument.
This way you don't have to define wrapper classes.

Bruno.

Jeff Louie said:
Use the ref keyword when you want to add another level of indirection.
You
can achieve the same effect by packing an object into a wrapper class.

5) Values and References to Objects are Passed By Value

By default, objects in C# are not passed by reference. (Unlike Java, C#
does
support passing by reference using the ref keyword.) In C#, you pass a
reference or a value to a method. You cannot pass an object to a method.
By
default, all calls to methods are by value. Now is that clear! In other
words,
you pass a reference to an object to a method, not the object itself.
The
reference is passed by value so that the a copy of the reference goes on
the
stack. The key here is that the object is not copied onto the stack and
you can
touch the object while inside the method. If you want to truly pass an
object
by reference (for a swap routine) use the ref keyword. Remember, you
cannot
pass an object, so you are actually passing a reference by reference.
Oh, I
have a headache.

Note: This topic has been a source of great confusion to C++ coders, so
I will
elaborate. If you want to write a swap routine then you need to add
another
degree of indirection to the method call. You can do this by use the
keyword
ref. Here is some sample code that demonstrates the concept. The swap
routine only works if you pass a reference to a concrete Drawable object
by
reference.

using System;

namespace TestSwap
{
abstract class Drawable
{
abstract public void DrawMe();
}
class Circle : Drawable
{
public override void DrawMe()
{
System.Console.WriteLine("Circle");
}
}
class Square : Drawable
{
public override void DrawMe()
{
System.Console.WriteLine("Square");
}
}
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static public void SwapByValue(Drawable d1, Drawable d2)
{
Drawable temp= d1;
d1 = d2;
d2= temp;
}
static public void SwapByRef(ref Drawable d1, ref
Drawable d2)
{
Drawable temp= d1;
d1 = d2;
d2= temp;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Drawable wasCircle= new Circle();
Drawable wasSquare= new Square();
wasCircle.DrawMe(); // outputs Circle
wasSquare.DrawMe(); // outputs Square
SwapByValue(wasCircle, wasSquare); // fails
wasCircle.DrawMe(); // outputs Circle
wasSquare.DrawMe(); // outputs Square
SwapByRef(ref wasCircle, ref wasSquare); //
succeeds
wasCircle.DrawMe(); // outputs Square
wasSquare.DrawMe(); // outputs Circle
System.Console.ReadLine();
}
}
}


You can mimic pass by reference in Java by "packing" the concrete
Drawable
object into a wrapper class. You can then pass a reference to the
packing
object to a swap routine by value. This added level of indirection
allows you
to implement a swap routine, so that you can swap the concrete Drawable
object in each packing object.

Regards,
Jeff
 
B

Bruno Jouhier [MVP]

Ori Anavim said:
Yes, i've read the article , but it doesn't answer to my question.
I will try to explain my self in a different way:

Jon's article really answers your question and it does it in a very precise
way, and I encourage you to read it carefully.

The problem with this subject is that expressions like "pass by reference"
have both a very precise technical definition and a layman interpretation
(passing the reference). Jon's article will tell you all the ins and outs of
the technical truth.

In layman terms, what you absolutely need to know is:

- In C#, you always pass refences to objects (*). Objects are never copied
when you pass them. If you want to copy them, you have to Clone() them
explicitly.

- The ref keyword is only useful if you want to *return* a different object
through the parameter. Here, I am really talking about returning "another"
object, not about modifying the same object. If you only want the method to
modify the same object, you *do not* need the ref keyword.

(*) Technically speaking, the reference is passed by value, which is
different from passing the object by reference. Here, Jon's article will
give you all the details.

So, in your example below, you only want to "modify" the object, you don't
want to "return" another object to the caller. So, you don't need any ref
keyword at all.

Bruno.
 
D

dilipdotnet at apdiya.com

Ori,
I think it does too... The ref keyword is not to state that you're
passing an object by value or by reference, but to state if that object
has been initialized or not. This only serves the purpose of catching
compile time exceptions if you pass in an object that is not initialied

eg.


public void foo(ref string var) {
....
}

public void someFn() {
string initialized = "";
string notInitialized;

foo(ref initialized); //<- OK!
foo(ref nonInitialized); //<- compile error
....
}

Hope that helps
}
 
J

Jon Skeet [C# MVP]

I think it does too... The ref keyword is not to state that you're
passing an object by value or by reference

Agreed, but only because you don't pass an *object* at all. The ref
keyword *is* to state that you're passing a *parameter* by reference as
opposed to by value.
but to state if that object has been initialized or not.

No, it doesn't state that at all. "out" parameters can be not
definitely assigned before the call (and must be definitely assigend in
the method before it returns normally), but ref has exactly the same
restrictions in terms of definite assignment as passing the parameter
by value.
This only serves the purpose of catching
compile time exceptions if you pass in an object that is not initialied

eg.

public void foo(ref string var) {
...
}

public void someFn() {
string initialized = "";
string notInitialized;

foo(ref initialized); //<- OK!
foo(ref nonInitialized); //<- compile error

That has nothing to do with ref - it would occur anyway. If you haven't
already read the article, I strongly suggest that you do :)
 
D

Dilip Krishnan

Duh! yr right... the ref and out doesnt make a copy and passes the
object by 'reference' :) Thanks your article is great
 

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