473,662 Members | 2,593 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Ref Propogation in C#

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.
Nov 15 '05 #1
12 1459
Ori <or*******@hotm ail.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2


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.
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #3
Ori Anavim <an********@hot mail.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4

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(MyO bject 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.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #5
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.

"Ori" <or*******@hotm ail.com> a écrit dans le message de
news:b4******** *************** ***@posting.goo gle.com...
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.

Nov 15 '05 #6
Ori Anavim <an********@hot mail.com> wrote:
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(MyO bject 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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #7
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("Circ le");
}
}
class Square : Drawable
{
public override void DrawMe()
{
System.Console. WriteLine("Squa re");
}
}
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static public void SwapByValue(Dra wable 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.DrawM e(); // outputs Circle
wasSquare.DrawM e(); // outputs Square
SwapByValue(was Circle, wasSquare); // fails
wasCircle.DrawM e(); // outputs Circle
wasSquare.DrawM e(); // outputs Square
SwapByRef(ref wasCircle, ref wasSquare); //
succeeds
wasCircle.DrawM e(); // outputs Square
wasSquare.DrawM e(); // 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

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #8
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" <je********@yah oo.com> a écrit dans le message de
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..
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("Circ le");
}
}
class Square : Drawable
{
public override void DrawMe()
{
System.Console. WriteLine("Squa re");
}
}
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static public void SwapByValue(Dra wable 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.DrawM e(); // outputs Circle
wasSquare.DrawM e(); // outputs Square
SwapByValue(was Circle, wasSquare); // fails
wasCircle.DrawM e(); // outputs Circle
wasSquare.DrawM e(); // outputs Square
SwapByRef(ref wasCircle, ref wasSquare); //
succeeds
wasCircle.DrawM e(); // outputs Square
wasSquare.DrawM e(); // 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

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #9
"Ori Anavim" <an********@hot mail.com> a écrit dans le message de
news:OI******** ******@tk2msftn gp13.phx.gbl...

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.
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(MyO bject 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.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1703
by: Annonce83 | last post by:
Good evening I will like to create a software on the grayline, I looking for information for this subject (calculation, code etc...) Thank your very much for your help. My best regards, Jean-Philippe
303
17593
by: mike420 | last post by:
In the context of LATEX, some Pythonista asked what the big successes of Lisp were. I think there were at least three *big* successes. a. orbitz.com web site uses Lisp for algorithms, etc. b. Yahoo store was originally written in Lisp. c. Emacs The issues with these will probably come up, so I might as well mention them myself (which will also make this a more balanced
2
2880
by: Ken Fine | last post by:
I'm trying to get DNS set up properly on my box under Win2kAS. I'm a DNS newbie, so please go easy. :) Everything appears to be (mostly) there, with one significant annoying exception. I've set up "mydomain.net" as a forward lookup zone in the DNS console. I've set up admin and www as hosts, so that I have subdomains: people can visit www.mydomain.net and admin.mydomain.net without a problem.
13
3651
by: Dennis Lubert | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi people, I want to create my own variant of a cout Object, so that I can use different of those for debugging... Like this class, but as a stream...
0
1502
by: anguo | last post by:
hi, everyone. i use mysql server version: 3.23.33. when i insert one line in a table, it can insert normaly. but then it display : null discard 9/udp sink null systat 11/tcp users daytime 13/tcp daytime 13/udp netstat 15/tcp
1
3465
by: Colin Hale | last post by:
I have a problem (amongst others)... I have the following code which sends 2 emails. I only want to send one! <A ONCLICK="OnActionClick('E-Mail')" ID="EMailNowAnchor" NAME="EMailNowAnchor" HREF="javascript:OnActionClick('E-Mail');" TABINDEX ="2"
0
1074
by: Simon Stewart \(C# MVP\) | last post by:
Hi Our scenario is: Various business objects on a server using interfaced-based remoting being called by a thick Windows client - all written in .NET 1.1. Objects are running under a domain admin/domain user account and hosted as a Windows Service on Windows 2003. In some situations, instead of receiving a "normal" exception or one of our custom exceptions we receive the following:
30
1904
by: fritz-bayer | last post by:
Hi, why does the php expression $result = 5543039447 & 2147483648; when executed evaluate to 0, whereas the perl expression $same = 5543039447 & 2147483648 ;
1
1160
by: Adam Clauss | last post by:
Consider the following code: try { methodA(); try { methodB(); }
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8344
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8764
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8546
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7367
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4180
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4347
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1752
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.