473,412 Members | 2,048 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,412 software developers and data experts.

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 2822
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(ArrayList 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(ArrayList 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**@discussions.microsoft.com> wrote in message
news:78**********************************@microsof t.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**@discussions.microsoft.com> wrote in message
news:78**********************************@microsof t.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
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...
58
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...
9
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...
8
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,...
13
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
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...
6
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...
12
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
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...
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: 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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
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...
0
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...

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.