473,804 Members | 2,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing by reference twice

If I am passing a variable by reference to another routine by reference, do
I need to dereference first?

string testString;
....

FirstSub(ref firstString)
{
HandleString(re f firstString); //do I need to de
reference here or just pass theString without the "ref"
}
void HandleString(re f theString)
{
Console.WriteLi ne(thestring);
}
Apr 18 '06
22 3506
Fabio wrote:
"tshad" <ts**********@f tsolutions.com> ha scritto nel messaggio
news:Ol******** ******@TK2MSFTN GP02.phx.gbl...
Because I am building the string in another function which can get fairly
large and I don't want to pass the actual string which will get very
large.

IMHO it is not a good design the use of "ref" in a method.
It only add confusion for the use of the method.


I agree that where possible, pass-by-reference should be avoided - but
sometimes it can make the code simpler.
For strings also, since they are immutable, there is no reasons to use ref.
That's not true. The following two methods have very different effects:

void ChangeMe (ref string x)
{
x = "foo";
}

void DontChangeMe (string x)
{
x = "foo";
}
Best a simple method following the designing guideline:

public string GetHandledStrin g(string myString)
{
myString = ...
return myString;
}


That's fine if you don't need the return value for something else.
Every so often, however, it is useful to use ref/out parameters. Look
at double.TryParse for an example of this. (That uses an out parameter,
but ref parameters can be useful in the same way.)

Jon

Apr 18 '06 #11
"Jon Skeet [C# MVP]" <sk***@pobox.co m> ha scritto nel messaggio
Best a simple method following the designing guideline:

public string GetHandledStrin g(string myString)
{
myString = ...
return myString;
}


That's fine if you don't need the return value for something else.
Every so often, however, it is useful to use ref/out parameters. Look
at double.TryParse for an example of this. (That uses an out parameter,
but ref parameters can be useful in the same way.)


You're right, but there are really few occasions that require ref/out.
And I think that also the Fw classes use it so rarely because maybe can make
code run faster, but not more clear.
Elsewhere all the Create<Somethin g>() methods would be Create<Somethin g>(out
Something x).

Don't you think so?

Apr 18 '06 #12
Fabio wrote:
That's fine if you don't need the return value for something else.
Every so often, however, it is useful to use ref/out parameters. Look
at double.TryParse for an example of this. (That uses an out parameter,
but ref parameters can be useful in the same way.)


You're right, but there are really few occasions that require ref/out.
And I think that also the Fw classes use it so rarely because maybe can make
code run faster, but not more clear.
Elsewhere all the Create<Somethin g>() methods would be Create<Somethin g>(out
Something x).

Don't you think so?


It's not that it can make code run faster - it's just that it's only
really useful if you've already used the return value for something
else.

As I said before, it's rarely useful - which is why it's not usually
considered a major omission from Java, for instance - but every so
often it can be pretty handy.

(It's also fairly useful with interop, IIRC. There are lots of Windows
APIs which do this kind of thing, but with pointers. Using ref/out is
the usualy way of handling this.)

Jon

Apr 18 '06 #13

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:11******** **************@ t31g2000cwb.goo glegroups.com.. .
Fabio wrote:
As I said before, it's rarely useful - which is why it's not usually
considered a major omission from Java, for instance - but every so
often it can be pretty handy.

(It's also fairly useful with interop, IIRC. There are lots of Windows
APIs which do this kind of thing, but with pointers. Using ref/out is
the usualy way of handling this.)
It's also useful for multiple-value returns:

ParseMyString( string str, out string part1, out string part2, out
string part3) ...

Of course, you can also provide a type for the return, and use the new
object initalizers (when 3.0 comes out...) to set up the return, alieviating
the need for c'tors or a temp:

struct ParseRet { string part1, part2, part3; }
ParseRet ParseMyString( string str)
{
...
return new ParseRet { part1 = ..., part2 = ...,part3 = ...}
}

I can't belive object and collection initializers have taken this long - but
I'll be glad to have them!

If/When c# gets tuple unpacking or generalized structure assignment (LHS
only unification) (a la Python, Ruby, etc.), you could do it this way:

part1, part2, part3 = ParseMyString( str); // 3-ary collection unpacked
and assigned

I thought this was in 3.0, but a glance at the currect spec leads me to
beleive it's not there. (Because "tuples" in c# are really anonymous, but
actual classes.)
But it would be cool if a collection/member destructuring assignment was
supplied, as that can be pretty powerful when needed.

There are probably some tricks with new features such as implicit typing,
anonymous types, etc., in combination w/generics that probably provide other
ways of returning multiple values that have different tradeoffs from the
current methods - but probably the most ideomatic in c# is to just define a
struct.

m

Jon

Apr 18 '06 #14

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Mart <ma***********@ simpl.co.nz> wrote:
In .NET, String is a Reference Type. It is allocated on the heap, and
the variable that you've declared (testString) contains it's address (a
pointer to it). This means that you will always be passing some form of
reference to the instance rather than the instance itself, whether you
pass the testString variable by ref or by value -- so I'm not sure that
you need to put the 'ref' bit in.


He does if the point is that a method lower down the call chain will
change the value of the parameter to be a different string. For
instance:

using System;

public class Test
{
static void Main()
{
string x = "hello";

Foo (ref x);
Console.WriteLi ne (x);
}

static void Foo (ref string y)
{
Bar (ref y);
}

static void Bar (ref string z)
{
z = "there";
}
}

The code actually being shown doesn't use this facility, admittedly,
and it looks like the OP does have misconceptions given his reluctance
to pass the string reference by value because "I don't want to pass the
actual string which will get very large".

Obligatory link for this kind of thread:
http://www.pobox.com/~skeet/csharp/parameters.html


Good article.

But I was a little confused when he was talking about value types. He uses
as his first example:

public struct IntHolder
{
public int i;
}

I would think a struct would be a reference type. I am assuming that this
is a value type because it only contains one value type (int). If it was
something like:

public struct IntHolder
{
public int i; public int j;
}
would it still be a value type?Thanks,Tom > > -- > Jon Skeet -
<sk***@pobox.co m>> http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet> If replying to the group, please do not
mail me too
Apr 18 '06 #15
In C#, structs are always value types. Do not confuse C# structs with,
say, C++ structs. They act completely differently.

Apr 18 '06 #16
tshad <ts**********@f tsolutions.com> wrote:
Obligatory link for this kind of thread:
http://www.pobox.com/~skeet/csharp/parameters.html
Good article.

But I was a little confused when he was talking about value types. He uses
as his first example:

public struct IntHolder
{
public int i;
}

I would think a struct would be a reference type.


No - the whole point of declaring something as a struct instead of a
class is to make it a value type instead of a reference type.

I am assuming that this is a value type because it only contains one value type (int). If it was
something like:

public struct IntHolder
{
public int i; public int j;
}
would it still be a value type?


Yes. It's a value type as long as it's declared as a struct instead of
a class.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 18 '06 #17


Jon Skeet [C# MVP] wrote:
Fabio wrote:
That's fine if you don't need the return value for something else.
Every so often, however, it is useful to use ref/out parameters. Look
at double.TryParse for an example of this. (That uses an out parameter,
but ref parameters can be useful in the same way.)


You're right, but there are really few occasions that require ref/out.
And I think that also the Fw classes use it so rarely because maybe can make
code run faster, but not more clear.
Elsewhere all the Create<Somethin g>() methods would be Create<Somethin g>(out
Something x).

Don't you think so?

It's not that it can make code run faster - it's just that it's only
really useful if you've already used the return value for something
else.

As a general rule in programming, I don't think that functions should be able to
create side-effects. Some languages will make sure it doesn't happen, some don't.

eg

classa fn1 ( ref classa a )
{
return operation_on_a;
}

classa thing = fn1 ( ref a ) + a

is dependent on how the compiler handles expressions. Now it could be that we
know C# does it one way, but C++ or D# might do it another way.

iow, if the value of parameters can be changed, they should only occur in void
functions.
Apr 18 '06 #18
Ian Semmel <is***********@ NOKUNKrocketcom p.com.au> wrote:
It's not that it can make code run faster - it's just that it's only
really useful if you've already used the return value for something
else.
As a general rule in programming, I don't think that functions should be able to
create side-effects. Some languages will make sure it doesn't happen, some don't.


Even if the variable values don't change, there's often nothing to stop
people manipulating referenced objects - adding to lists, etc.

Side-effects *can* be very useful - they just shouldn't be overused
(just like plenty of other things).
eg

classa fn1 ( ref classa a )
{
return operation_on_a;
}

classa thing = fn1 ( ref a ) + a

is dependent on how the compiler handles expressions. Now it could be that we
know C# does it one way, but C++ or D# might do it another way.
Some languages don't define it; C# does, fortunately.
iow, if the value of parameters can be changed, they should only occur in void
functions.


I'd say the example above is certainly bad style just in terms of
readability, but I don't think it's anything that should be restricted
in the language.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 18 '06 #19

"Ian Semmel" <is***********@ NOKUNKrocketcom p.com.au> wrote in message
news:Oz******** ******@TK2MSFTN GP05.phx.gbl...


Jon Skeet [C# MVP] wrote:
Fabio wrote:
That's fine if you don't need the return value for something else.
Every so often, however, it is useful to use ref/out parameters. Look
at double.TryParse for an example of this. (That uses an out parameter,
but ref parameters can be useful in the same way.)

You're right, but there are really few occasions that require ref/out.
And I think that also the Fw classes use it so rarely because maybe can
make
code run faster, but not more clear.
Elsewhere all the Create<Somethin g>() methods would be
Create<Somet hing>(out
Something x).

Don't you think so?

It's not that it can make code run faster - it's just that it's only
really useful if you've already used the return value for something
else.

As a general rule in programming, I don't think that functions should be
able to create side-effects. Some languages will make sure it doesn't
happen, some don't.

eg

classa fn1 ( ref classa a )
{
return operation_on_a;
}

classa thing = fn1 ( ref a ) + a

is dependent on how the compiler handles expressions. Now it could be that
we know C# does it one way, but C++ or D# might do it another way.

iow, if the value of parameters can be changed, they should only occur in
void functions.


I think a success/failure or status return is quite handy:

if ( DoSomething( a, b, ref out c, ref out d))
// we're golden

This was especially true before nullable values, where it may be hard to
determine from the out params whether the function even suceeded if results
are allowed to be null.
As most functional languages have an implcit notion of success/failure
(where failure sometimes results in backtracking if the language supports
it) even if programming c# in a functional style, I don't think returning
true/false is so bad.

m

Apr 18 '06 #20

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

Similar topics

58
10188
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);
25
2948
by: Victor Bazarov | last post by:
In the project I'm maintaining I've seen two distinct techniques used for returning an object from a function. One is AType function(AType const& arg) { AType retval(arg); // or default construction and then.. // some other processing and/or changing 'retval' return retval; }
6
8832
by: keepyourstupidspam | last post by:
Hi, I want to pass a function pointer that is a class member. This is the fn I want to pass the function pointer into: int Scheduler::Add(const unsigned long timeout, void* pFunction, void* pParam)
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:
6
6003
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
2691
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);
7
3314
by: TS | last post by:
I was under the assumption that if you pass an object as a param to a method and inside that method this object is changed, the object will stay changed when returned from the method because the object is a reference type? my code is not proving that. I have a web project i created from a web service that is my object: public class ExcelService : SoapHttpClientProtocol {
8
1379
by: Sanders Kaufman | last post by:
I think I finally get the idea of passing by reference, but I'm struggling with the syntax and grammar of it. I've got an object and I want to send it to a function to have its properties modified like so: class MyClass { var $a; function MyClass(){
8
3509
by: S. | last post by:
Hi all, Can someone please help me with this? I have the following struct: typedef struct { char *name; int age; } Student;
0
9594
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
10599
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
10346
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
10347
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
10090
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...
1
7635
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
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
3832
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.