473,718 Members | 2,116 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using ref

Hi,

Form a performance perspective, is it wise to use the ref statement as much
as possible?

Thanks!
Arjen

Jul 2 '08 #1
65 3904
The objects themselves are passed by reference anyway, so I would think that
using "ref" would actually slow things down a tiny bit (adds one more level
of indirection.

I only use "ref" when I need to reseat the variable to point to a different
object.

- Steve

"Arjen" <bo*****@hotmai l.comwrote in message
news:1B******** *************** ***********@mic rosoft.com...
Hi,

Form a performance perspective, is it wise to use the ref statement as
much
as possible?

Thanks!
Arjen

Jul 2 '08 #2
Steve Harclerode <Li************ *@hot.mail.comw rote:
The objects themselves are passed by reference anyway
No, they're not. The references are passed by value. There's a big
difference. See
http://pobox.com/~skeet/csharp/parameters.html
I only use "ref" when I need to reseat the variable to point to a different
object.
Exactly.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 2 '08 #3

"Jon Skeet [C# MVP]" <sk***@pobox.co mschreef in bericht
news:MP******** *************@m snews.microsoft .com...
Steve Harclerode <Li************ *@hot.mail.comw rote:
>The objects themselves are passed by reference anyway

No, they're not. The references are passed by value. There's a big
difference. See
http://pobox.com/~skeet/csharp/parameters.html
>I only use "ref" when I need to reseat the variable to point to a
different
object.

Exactly.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Thank you!

Jul 2 '08 #4
On Jul 2, 2:12*pm, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
--
I agree with Jon Skeet here. A ref should be used when you have a
reference-type object passed to your function, which usually means
something that is instantiated with "new" in the function. But, if
you don't use "new" in your method/function for the object passed to
it, then use the default pass by value. Interestingly enough, both
pass by value and pass by reference *will* both alter the object
passed *outside* the function/method--the opposite is usually implied
in most textbook examples. In most examples it is stated that only
pass by reference will alter the object-- with usually the famous
'swap variables' example using 'temp' given--but what most people
don't realize is that this swap variable example is using 'new' inside
the function/method (check it out next time you see it, and you'll see
that's the case), which is exactly when you should use 'ref'--
otherwise stick to the default pass-by-value. If 'new' is not being
used for the object passed, use the default pass-by-value, as it's
slightly faster, as implied in this thread. The only exception to the
above is when primitive values (int, double, etc) are passed to a
function/method--but here, this seems to be an exception because these
are value-type parameters stored on the stack rather than heap, so
boxing/unboxing is involved. Technically, you could box these
primitive value-type parameters as reference-type objects, then there
would be no 'exception'. Anyway, it usually doesn't make sense to
refer to 'ref' when passing an int parameter to a method/function
anyway, so this is really not an exception to the rule.

In short, the rule is this: when using 'new' inside your method, to
instantiate a object being passed to the method (in the parameters
list), then use the 'ref' keyword in the parameters, to pass by
reference, otherwise, stick with the default (no keyword) pass-by-
value.

If the above doesn't make sense, don't worry about it--just keep
programming and it will become clear eventually.

Ray Lopez
[C# N00b MVP]
Jul 2 '08 #5
I've read the page, but I still don't see how my languaging would be
considered different than "references are passed by value". What part of
what I wrote isn't correct?

Genuinely interested,
Steve

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
Steve Harclerode <Li************ *@hot.mail.comw rote:
>The objects themselves are passed by reference anyway

No, they're not. The references are passed by value. There's a big
difference. See
http://pobox.com/~skeet/csharp/parameters.html

Jul 3 '08 #6
On Jul 3, 7:33*am, "Steve Harclerode" <Camel.Software ...@hot.mail.co m>
wrote:
I've read the page, but I still don't see how my languaging would be
considered different than "references are passed by value". What part of
what I wrote isn't correct?
When a parameter is passed by reference, that means that changes to
the parameter are reflected in the variable used as the argument. When
a reference is passed by value, that's not the case.

So consider this code:

public void Swap (object a, object b)
{
object tmp = a;
a = b;
b = a;
}

If the parameter were passed by reference by default, that would work.
As it is, it does nothng.

The *object* isn't actually passed at all, which is another reason
that "objects are passed by reference" is incorrect. In particular,
consider the case where the reference is actually null. What's being
passed and in what way at that point?

It's a clearer and more accurate mental model to talk about references
being passed by value. It avoids confusing people who understand what
"by reference" means, and would expect the Swap method above to work
when presented with your description. (I've seen this happen on
various occasions.) It also makes it very confusing when you add the
"ref" parameter for a reference type - if things were already being
passed by reference, what would adding "ref" do?

Jon
Jul 3 '08 #7
On Wed, 02 Jul 2008 23:33:57 -0700, Steve Harclerode
<Ca************ ***@hot.mail.co mwrote:
I've read the page, but I still don't see how my languaging would be
considered different than "references are passed by value". What part of
what I wrote isn't correct?
You wrote "objects are passed by reference". But _all_ parameters,
including references to objects, are passed _by value_, except when using
"ref" and "out" of course.

The fact that the value you're passing is a reference does not make the
parameter a "by reference" parameter, nor does it mean that the object is
passed by reference.

IMHO, Jon's article does in fact explain this.

Pete
Jul 3 '08 #8
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:ef******** *************** ***********@s50 g2000hsb.google groups.com...
public void Swap (object a, object b)
{
object tmp = a;
a = b;
b = a;
}

If the parameter were passed by reference by default, that would work.
As it is, it does nothng.
Thinking back on my Pascal days, by golly you're right (you probably knew
that already).
It's a clearer and more accurate mental model to talk about references
being passed by value. It avoids confusing people who understand what
It is a better mental model, I'll use it the next time I have to mentor a
new person. God help the others I've already worked with. Actually, they
seem to be doing all right, so hopefully they absorbed the correct
information somewhere.
:-)

- Steve
Jul 3 '08 #9
Jon,

I have to disagree with you that objects themselves are passed by value.
Passing by value means that you pass the value; i.e. a byte[] (or Vector, or
Hashtable) being passed as value passes the entire thing - that doesn't
happen. Also, passing by value means that the thing cannot be changed;
hence passing by value not reference. But when you do "method (list)",
method can change list because a reference to the list is being passed, not
the list (aka value). C# simple passes a reference to the object which is
the same as C passing in a pointer to the data. And the method cannot
change the reference in C# just as the method in C cannot change the pointer
(from the caller's point of view) - same thing.

Pass by reference:
C# - passes a reference to the data (not the data) and the data can be
changed by the method
C - passes a pointer to the data (not the data) and the data can be changed
by the method

The example you give on your page "method (StringBuilder x)" then "x = null"
is exactly the same as C having "method (int *x)", then "x = NULL"; i.e.
pass by reference. If you view "x" as a reference to the StringBuilder
object, then you're passing the object by reference (which you said did not
happen). If you view "x" as the actual StringBuilder object, then the VM is
effectively passing &x (C terminology) - again, by reference. It uses
ldloca.s which is defined as "Loads the address of the local variable at a
specific index onto the evaluation stack, short form." - same as C.

Apart from ints, floats, etc, C# passes all objects by reference. "ref"
simply passes the address of the reference thereby allowing the method to
change it (exactly the same as C). "out" is the same as "ref" except that
the method is forced, by the compiler, to assign a value to the parameter.

How is this C code that uses pass by reference:

byte* b = {some array of bytes};
method (b);

....different to this C# code?

byte[] b = new byte[]{some array of bytes};
method (b);

In a meeting, would you ever say "Add the two string references together to
get the filename"? I wouldn't, I'd say "Add the two strings together to get
the filename". So, if we view "s" as a string, then "method (s)" is pass by
reference.

Jon, Peter, before you reply, I know that most of the literature out there
agrees with your point of view, so no need to rehash what they have already
written. Maybe it's just me, but I cannot see how C# passes objects by
value.

Hilton
Jul 3 '08 #10

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

Similar topics

5
5713
by: Enos Meroka | last post by:
Hallo, I am a student doing my project in the university.. I have been trying to compile the program using HP -UX aCC compiler, however I keep on getting the following errors. ================================================================= Error 19: "CORBAManagerMessages.h", line 4 # Unexpected 'std'. using std::string; ^^^
3
2163
by: Mike L | last post by:
Should the command call "using" be before or after my namespace? **AFTER** namespace DataGridBrowser { using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections;
3
2441
by: xzzy | last post by:
I was wondering why we have to have using System.Data using System.Configuration using etc.... why are they not all lumped into one 'using'? In other words, is there a best way to use project classes with 'using' meaning
14
5799
by: pmud | last post by:
Hi, I need to use an Excel Sheet in ASP.NET application so that the users can enter (copy, paste ) large number of rows in this Excel Sheet. Also, Whatever the USER ENETRS needs to go to the SQL DATABASE, probably by the click of a button. Is this possible? & what is the BEST APPROACH for doing this? & also if any links are there do tell those to me too coz I have no idea how to go about doing it.
8
2413
by: acb | last post by:
Hi, I wrote a DLL Component (using Visual Studio 2005) and managed to include it into a C# Console application. I am now trying to include this component into a Web project. I copy the DLL into the bin directory but am not able to progress. Can anyone please guide me to an online tutorial on the subject. Thanks,
0
2207
by: Metal2You | last post by:
I'm working on an ASP.NET 2.0 application in Visual Studio 2005 that accesses a Sybase database back end. We're using Sybase SQL Anywhere 9.0.2.3228. I have installed and registered the Sybase .NET 2.0 DataProvider (iAnywhere.Data.AsaClient.dll) into the GAC so it can be used in the ProviderName property of a SQLDataSource and loads properly at run time. The application I'm writing is a bit more complex than the example I'm about to...
10
1962
by: mg | last post by:
I'm migrating from VB6 and have a question about using 'Using' and the best way to use it. Here is a example of a small bit of code: dbConx("open") Using CN Dim CMD As New OleDbCommand(sSQL, CN) Dim DR As OleDbDataReader = CMD.ExecuteReader()
0
2567
by: Eugene Anthony | last post by:
The problem with my coding is that despite removing the records stored in the array list, the rptPages repeater control is still visible. The rptPages repeater control displayes the navigation link (1,2,3 so on). The code can be found in SubscriptionCart.aspx.cs. Default.aspx ------------
3
8291
by: JDeats | last post by:
I have some .NET 1.1 code that utilizes this technique for encrypting and decrypting a file. http://support.microsoft.com/kb/307010 In .NET 2.0 this approach is not fully supported (a .NET 2.0 build with these methods, will appear to encrypt and decrypt, but the resulting decrypted file will be corrupted. I tried encrypting a .bmp file and then decrypting, the resulting decrypted file under .NET 2.0 is garbage, the .NET 1.1 build works...
6
5164
by: =?Utf-8?B?U2hhd24gU2VzbmE=?= | last post by:
Greetings! I was researching AJAX to provide a solution to displaying status messages while a long process executed. I found several examples online and was able to use their code to get a quick application working. However, when attempting to implement the solution, the AJAX calls weren't updating the screen like the examples were and seemed not to fire until after the long running process had completed. I found the only real...
0
8827
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
9207
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
9120
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
9053
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7987
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...
1
6652
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5971
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();...
0
4741
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2122
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.