473,769 Members | 1,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing reference type with 'ref' vs. without

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 those
changes.
But if one adds "ref" keyword the actual address of a variable that holds
object's reference is passed in, Which accomplishes the same thing as above
scenario (without ref), but far more dangerous. My questions:

1. Is my overall understanding accurate?
2. What are some practical (real life) usages for passing reference type
with ref.
3. Is there any performance benefits ref vs. without ref.
Thanks
Nov 17 '05 #1
6 2846
Lenn wrote:
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 those
changes.
But if one adds "ref" keyword the actual address of a variable that holds
object's reference is passed in, Which accomplishes the same thing as above
scenario (without ref), but far more dangerous. My questions:

1. Is my overall understanding accurate?
I'm not sure, but maybe not quite. The thing is this: when you use the
ref keyword, the parameter passed is a reference to whatever there was
before, regardless of whether that was already a reference type or not.
2. What are some practical (real life) usages for passing reference type
with ref.
Think of it like this: most of the time you use functions that return
values:

int Foo() {
return 42;
}

...
int bar = Foo(); // bar is now 42

You could achieve the exact same result by going:

void Foo(ref int parm) {
parm = 42;
}

...
int bar;
Foo(ref bar); // bar is now 42

The main difference is that it's possible to have more than one
parameter at a time that is set in this way, which is not possible with
"normal" return values (in C# that is, it's perfectly possible in other
languages). C# strives to make this visible to the programmer who calls
such a method by making it mandatory to use the ref keyword on the
method signature as well as for the method call.

I think if ref parameters are used in a responsible manner, they can be
a useful tool in specific circumstances. But these circumstances are
really quite specific indeed - always consider these questions:

a) Are you sure that the method in question must calculate several
values for you at once? Is this the best implementation?

b) If you said yes to (a), wouldn't it be a better idea to find some
encapsulation for the data in question, like a class or struct that
holds the various values?

Personally, I haven't used ref parameters for quite a while, because I
rarely find the specific situation where they seem to be the best solution.

3. Is there any performance benefits ref vs. without ref.


You can't really ask the question like that - either you need them or
you don't. Generally speaking, I don't think there's a benefit or
penalty either way. It's just one more pointer, after all, whatever they
call it :-)

Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619 http://www.sturmnet.org/blog
Nov 17 '05 #2
The difference between the two is that you can alter what a ref
parameter points to. Consider the following example:

public void RefVar(ref MyClass x, MyClass y)
{
x = new MyClass(); //x will now point to this new class instance
inside and ouside this method scope
y = new MyClass(); //will only point to this new class instance
inside this method scope
}

Usually ref variables are used in procedures that do initialization of
objects (means the method should accept a null reference). A "factory"
type procedure could do this (although usually you'd just use the
return value).

Performance is not a factor when deciding whether to pass ref
arguments, it just depends on what your function needs to do.

Nov 17 '05 #3
> Could someone clarify my confusion regarding passing reference types to a
method with ref keyword and explain when it's practical to use it.
The reference itself can be updated if passed with "ref".

void Function1(ref x)
{
// Affects the function calling it; it's X now points to Y.
x = y;
}

void ByVal(x)
{
// Affects only our local x.
x = y;
}
For a better explanation ee this article by Jon Skeet:
http://www.yoda.arachsys.com/csharp/parameters.html
scenario (without ref), but far more dangerous. My questions:
Dangerous? Why dangerous?
1. Is my overall understanding accurate?
Yeah I think so.
2. What are some practical (real life) usages for passing reference type
with ref.
If you wish to return two new references. There's only one return value,
so you'd have to use a ref or out parameter to pass the reference back to
the caller.
3. Is there any performance benefits ref vs. without ref.

Without ref would use one lesser dereference. But I don't think that
matters at all, in normal scenarios.

Greetings,
Wessel
Nov 17 '05 #4
The point of the ref keyword is to allow you to change the object that is
being passed into the method inside the method.

For example:

void DoSomething(Arr ayList exampleList)
{
exampleList.Add ("Something" );
}

The caller of this method will see the changes made to the arraylist....
i.e. it will see the new entry.

However, with

void DoSomething(Arr ayList exampleList)
{
exampleList = new ArrayList();
exampleList.Add ("Something" );
}

the caller will not see the new item as the reference inside the method has
changed. For the caller to be able to see the new item in the new list the
method signature would be:

void DoSomething(ref ArrayList exampleList)

And, ref is used for allowing you to pass value types by reference.

"Lenn" wrote:
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 those
changes.
But if one adds "ref" keyword the actual address of a variable that holds
object's reference is passed in, Which accomplishes the same thing as above
scenario (without ref), but far more dangerous. My questions:

1. Is my overall understanding accurate?
2. What are some practical (real life) usages for passing reference type
with ref.
3. Is there any performance benefits ref vs. without ref.
Thanks

Nov 17 '05 #5
Others have explained well with examples.

One way to think about it, is that C# (as well as Java, Lisp, Python,
etc...) by default (or without exception) pass
*object references by value*.
By specifiying "ref" you can pass a reference (address) of something that
holds an object reference. When passing a C# struct you pass an object by
value.

m
"Lenn" <Le**@discussio ns.microsoft.co m> wrote in message
news:78******** *************** ***********@mic rosoft.com...
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 those
changes.
But if one adds "ref" keyword the actual address of a variable that holds
object's reference is passed in, Which accomplishes the same thing as
above
scenario (without ref), but far more dangerous. My questions:

1. Is my overall understanding accurate?
2. What are some practical (real life) usages for passing reference type
with ref.
3. Is there any performance benefits ref vs. without ref.
Thanks

Nov 17 '05 #6
Others have explained well with examples.

One way to think about it, is that C# (as well as Java, Lisp, Python,
etc...) by default (or without exception) pass
*object references by value*.
By specifiying "ref" you can pass a reference (address) of something that
holds an object reference. When passing a C# struct you pass an object by
value.

m
"Lenn" <Le**@discussio ns.microsoft.co m> wrote in message
news:78******** *************** ***********@mic rosoft.com...
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 those
changes.
But if one adds "ref" keyword the actual address of a variable that holds
object's reference is passed in, Which accomplishes the same thing as
above
scenario (without ref), but far more dangerous. My questions:

1. Is my overall understanding accurate?
2. What are some practical (real life) usages for passing reference type
with ref.
3. Is there any performance benefits ref vs. without ref.
Thanks

Nov 17 '05 #7

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

Similar topics

5
36414
by: Andy | last post by:
Hi Could someone clarify for me the method parameter passing concept? As I understand it, if you pass a variable without the "ref" syntax then it gets passed as a copy. If you pass a variable with the "ref" syntax then it gets passed as a reference to the object and any changes to
58
10179
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
9
2299
by: Just Me | last post by:
PARAFORMAT2 is a structure that SendMessage will return stuff in. Is the "ref" correct or since only a pointer is being passed should it be by value? Suppose I was passing data rather then receiving it, would that change the answer to the above?
8
2118
by: Dennis Myrén | last post by:
I have these tiny classes, implementing an interface through which their method Render ( CosWriter writer ) ; is called. Given a specific context, there are potentially a lot of such objects, each requiring a call to that method to fulfill their purpose. There could be 200, there could be more than 1000. That is a lot of references passed around. It feels heavy. Let us say i changed the signature of the interface method to:
13
2797
by: Maxim | last post by:
Hi! A have a string variable (which is a reference type). Now I define my Method like that: void MakeFullName(string sNamePrivate) { sNamePrivate+="Gates" }
5
1653
by: blue | last post by:
We often get connection pooling errors saying that there are no available connections in the pool. I think the problem is that we are passing around open readers all over the place. I am planning on changing this in our code and I expect this to fix our problem. We have our connection pooling set to the default number of connections open. We probably have about 3-7 users concurrently using our web site. So, the problem isn't that we...
6
5999
by: MSDNAndi | last post by:
Hi, I get the following warning: "Possibly incorrect assignment to local 'oLockObject' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local." My code is: using System; using System.Collections.Generic;
12
2685
by: Andrew Bullock | last post by:
Hi, I have two classes, A and B, B takes an A as an argument in its constructor: A a1 = new A(); B b = new B(a1);
11
7196
by: Bob Yang | last post by:
Hi, I have this in C++ and I like to call it from c# to get the value but I fail. it will be good if you can give me some information. I tried it in VB.net it works but I use almost the same way as VB in C# but it doens't work. c++: (csp2.dll) NoMangle long DLL_IMPORT_EXPORT csp2TimeStamp2Str(unsigned char *Stamp, char *value, long nMaxLength);
0
9423
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
10211
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
10045
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
7408
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
6673
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
5298
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
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.