473,385 Members | 1,325 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Using 'ref' when already reference variable

Is there any harm in passing an object into a method with the 'ref'
keyword if the object is already a reference variable? If not, is
there any benefit?

Nov 8 '05 #1
11 2154
Doug wrote:
Is there any harm in passing an object into a method with the 'ref'
keyword if the object is already a reference variable? If not, is
there any benefit?


That is the default for objects.
Nov 9 '05 #2
Using 'ref' for an object means that the method may change which object is
being pointed to. So, yes - there is some harm in using 'ref' when you don't
want to allow the method to change which object is being pointed to.

But you may not have a choice - if the method has a 'ref' param, you must
use the 'ref' keyword on the argument (in C#).
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB.NET to C# Converter
Instant VB: C# to VB.NET Converter
Instant C++: C# to C++ Converter
Instant J#: VB.NET to J# Converter

"Doug" wrote:
Is there any harm in passing an object into a method with the 'ref'
keyword if the object is already a reference variable? If not, is
there any benefit?

Nov 9 '05 #3
"John A. Bailo" <ja*****@texeme.com> wrote:
Is there any harm in passing an object into a method with the 'ref'
keyword if the object is already a reference variable? If not, is
there any benefit?


That is the default for objects.


Actually the default (for everything) is *by-value* passing. See
<http://www.yoda.arachsys.com/csharp/parameters.html>.
Nov 9 '05 #4
Cool Guy wrote:
"John A. Bailo" <ja*****@texeme.com> wrote:

Is there any harm in passing an object into a method with the 'ref'
keyword if the object is already a reference variable? If not, is
there any benefit?


That is the default for objects.

Actually the default (for everything) is *by-value* passing. See
<http://www.yoda.arachsys.com/csharp/parameters.html>.


I guess (from your article) this is what I meant to say:

"This difference is absolutely crucial to understanding parameter
passing in C#, and is why I believe it is highly confusing to say that
objects are passed by reference by default instead of the correct
statement that object references are passed by value by default."
Nov 9 '05 #5
All of this has been very helpful, but has lead me to another question.
Say I have a method like so:

private bool TestMethod(myFirstClass oFirstClass, mySecondClass
oSecondClass, myThirdClass oThirdClass)
{
...code here
}

and I'm not concerned with whether or not they set the value of those
objects to null inside this method or not but do want them to have the
ability to modify properties of the three class within them (which they
can regardless if they pass the parameters with the 'ref' keyword or
not).

What I am concerned with is that I may call this method many, many
times under different threads. From what I understand of the reading I
did of the document you put in your response, that would mean that each
time this method is called a new instance of each class is created of
the variables since they are not passed with the 'ref' keyword. From a
memory point of view this would be bad wouldn't it?

Nov 9 '05 #6
Doug <dn******@dtgnet.com> wrote:
private bool TestMethod(myFirstClass oFirstClass, mySecondClass
oSecondClass, myThirdClass oThirdClass)
{
...code here
}

[...]

From what I understand of the reading I
did of the document you put in your response, that would mean that each
time this method is called a new instance of each class is created of
the variables since they are not passed with the 'ref' keyword.


Your understanding is wrong. No new instances are created whether or not
'ref' is used.

Consider (MyClass is a class):

void Foo(MyClass myClass) {
...
}

When myClass is passed, it is passed by value. The value that is passed is
an /object reference/, since MyClass is a reference type. (An
/object reference/ is like a pointer to an object on the heap.)

Consider (MyClass is a class):

void Foo(ref MyClass myClass) {
...
}

When myClass is passed, it is passed by reference. The passed reference
**refers to** the /object reference/. (A reference to an /object reference/
is kind of like a pointer to a pointer.)

If this still isn't clear perhaps try reading the article I linked to
*again*, asking here about any parts you're unsure about.
Nov 9 '05 #7
Thanks. I figured out after I posted previously that I still didn't
get it. It's a pointer thing and I always get confused by that. But I
think I got it now. Thank you!

Nov 9 '05 #8
Cool Guy wrote:
When myClass is passed, it is passed by reference. The passed reference
**refers to** the /object reference/. (A reference to an /object reference/
is kind of like a pointer to a pointer.)


Well, isn't it just more like a pointer to an object -- or value?

Another thing, they say it's an object reference passed by value to the
method.

Ok, so that means if the object(class instance) gets an update (member
changes) that when I use the handle to the object, it should reflect the
updated value. Right?

And can if you did use the 'ref' keyword, wouldn't it then pass an
object reference to an object by reference instead of by value?

That would mean that would be more like a pointer to a pointer. What
that means is that I could change the object that is being pointed to by
the first pointer and the second reference would automatically be
pointing to that 2nd object.
Nov 9 '05 #9
"John A. Bailo" <ja*****@texeme.com> wrote:
Cool Guy wrote:
When myClass is passed, it is passed by reference. The passed reference
**refers to** the /object reference/. (A reference to an /object reference/
is kind of like a pointer to a pointer.)
Well, isn't it just more like a pointer to an object -- or value?


That sounds more like the case where ref *isn't* used. In the part you
quoted I was referring to it being used.
Another thing, they say it's an object reference passed by value to the
method.
In the case of ref *not* being used, yeah.
Ok, so that means if the object(class instance) gets an update (member
changes) that when I use the handle to the object, it should reflect the
updated value. Right?
Yep. That's why the following works prints 'testing', not 'test':

using System;
using System.Text;

class Test {
static void Main() {
StringBuilder sb = new StringBuilder("test");
Append(sb);
Console.WriteLine(sb);
}

static void Append(StringBuilder sb) {
sb.Append("ing");
}
}
And can if you did use the 'ref' keyword, wouldn't it then pass an
object reference to an object by reference instead of by value?
An object reference would be passed to a method by reference instead of by
value.
That would mean that would be more like a pointer to a pointer. What
that means is that I could change the object that is being pointed to by
the first pointer and the second reference would automatically be
pointing to that 2nd object.


Indeed. This is how I tend to visualise it (with the arrows meaning 'refers
to'):

reference --> object reference --> object (on heap)

The object reference in the middle can be changed via the reference on the
left to refer to another object on the heap (or null).

For example, in the following 'False' is printed:

using System;
using System.Text;

class Test {
static void Main() {
StringBuilder sb = new StringBuilder("test");
StringBuilder original = sb;

PseudoAppend(ref sb);
Console.WriteLine(Object.ReferenceEquals(sb, original));
}

static void PseudoAppend(ref StringBuilder sb) {
// modify the original object reference to refer to
// a new object
sb = new StringBuilder("testing");
}
}

Had the StringBuilder been passed by value instead (i.e. had 'ref' not been
used) 'True' would've been printed as the object reference Main.sb would
not have been modifiable from within PseudoAppend.
Nov 10 '05 #10

This pretty much answers all cases /except/ how do you pass an object by
value...where it clones the object so I can make changes to it without
changing the original?
Cool Guy wrote:
"John A. Bailo" <ja*****@texeme.com> wrote:

Cool Guy wrote:

When myClass is passed, it is passed by reference. The passed reference
**refers to** the /object reference/. (A reference to an /object reference/
is kind of like a pointer to a pointer.)


Well, isn't it just more like a pointer to an object -- or value?

That sounds more like the case where ref *isn't* used. In the part you
quoted I was referring to it being used.

Another thing, they say it's an object reference passed by value to the
method.

In the case of ref *not* being used, yeah.

Ok, so that means if the object(class instance) gets an update (member
changes) that when I use the handle to the object, it should reflect the
updated value. Right?

Yep. That's why the following works prints 'testing', not 'test':

using System;
using System.Text;

class Test {
static void Main() {
StringBuilder sb = new StringBuilder("test");
Append(sb);
Console.WriteLine(sb);
}

static void Append(StringBuilder sb) {
sb.Append("ing");
}
}

And can if you did use the 'ref' keyword, wouldn't it then pass an
object reference to an object by reference instead of by value?

An object reference would be passed to a method by reference instead of by
value.

That would mean that would be more like a pointer to a pointer. What
that means is that I could change the object that is being pointed to by
the first pointer and the second reference would automatically be
pointing to that 2nd object.

Indeed. This is how I tend to visualise it (with the arrows meaning 'refers
to'):

reference --> object reference --> object (on heap)

The object reference in the middle can be changed via the reference on the
left to refer to another object on the heap (or null).

For example, in the following 'False' is printed:

using System;
using System.Text;

class Test {
static void Main() {
StringBuilder sb = new StringBuilder("test");
StringBuilder original = sb;

PseudoAppend(ref sb);
Console.WriteLine(Object.ReferenceEquals(sb, original));
}

static void PseudoAppend(ref StringBuilder sb) {
// modify the original object reference to refer to
// a new object
sb = new StringBuilder("testing");
}
}

Had the StringBuilder been passed by value instead (i.e. had 'ref' not been
used) 'True' would've been printed as the object reference Main.sb would
not have been modifiable from within PseudoAppend.

Nov 10 '05 #11
"John A. Bailo" <ja*****@texeme.com> wrote:
This pretty much answers all cases /except/ how do you pass an object by
value...where it clones the object so I can make changes to it without
changing the original?


You could make it a struct instead of a class. Then the *value* gets passed
by value instead of the *reference* getting passed by value.

Or you could make the class immutable - then no state can be changed
anyway.

Or you could manually clone the instance and then pass the reference to
this *cloned* instance instead of passing the reference to the *original*
instance.
Nov 10 '05 #12

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

Similar topics

10
by: Tony Johansson | last post by:
Hello Experts!! This class template and main works perfectly fine. I have this class template called Handle that has a pointer declared as T* body; As you can see I have a reference counter in...
4
by: Edward Diener | last post by:
My undersstanding of using a ref parameter is to be able to pass initialized value variables as references. Is there any purpose to using a ref paraneter with a reference variable ? If one does it...
12
by: Priyesh | last post by:
public class stringtemp { String k ; public stringtemp(ref String inp) { k = inp ; } public void Change() { k = k.Remove(0, 1) ;
6
by: Lenn | last post by:
Hi, Could someone clarify my confusion regarding passing reference types to a method with ref keyword and explain when it's practical to use it. It's my understanding that in .NET reference...
7
by: Doug | last post by:
Is there any harm in passing an object into a method with the 'ref' keyword if the object is already a reference variable? If not, is there any benefit?
11
by: Doug | last post by:
Is there any harm in passing an object into a method with the 'ref' keyword if the object is already a reference variable? If not, is there any benefit?
22
by: Daniel Rucareanu | last post by:
I have the following script: function Test(){} Test.F = function(){} Test.F.FF = function(){} Test.F.FF.FFF = function(){} Test.F.FF.FFF.FFFF = function(){} //var alias = function(){}; var...
6
by: semkaa | last post by:
Can you explain why using ref keyword for passing parameters works slower that passing parameters by values itself. I wrote 2 examples to test it: //using ref static void Main(string args) {...
65
by: Arjen | last post by:
Hi, Form a performance perspective, is it wise to use the ref statement as much as possible? Thanks! Arjen
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.