473,768 Members | 8,216 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2199
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.arachs ys.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.arachs ys.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(myFi rstClass 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******@dtgne t.com> wrote:
private bool TestMethod(myFi rstClass 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.WriteLi ne(sb);
}

static void Append(StringBu ilder 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(re f sb);
Console.WriteLi ne(Object.Refer enceEquals(sb, original));
}

static void PseudoAppend(re f 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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2276
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 the class template so I know how many references I have to the body. In my case it's the Integer wrapper class which is the body. This template works for many different types. The one that I use is named Integer and is a Wrapper for an int. The...
4
4158
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 the compiler accepts it. Does this mean anything ?
12
1359
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
2845
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 types hold a reference to an object as opposed to object data itself. So, when reference type parameter is passed into a method, a copy of objects reference is passed in, so called method can do whatever to "original" object and a caller will see...
7
1666
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
425
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
2064
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 alias = Test.F.FF.FFF.FFFF;
6
3681
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) { List<TimeSpantimes = new List<TimeSpan>(); DateTime start; DateTime end; for (int j = 0; j < 1000; j++)
65
3925
by: Arjen | last post by:
Hi, Form a performance perspective, is it wise to use the ref statement as much as possible? Thanks! Arjen
0
9576
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
9407
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
10175
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10017
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
9961
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
6656
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3932
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
3534
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2808
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.