473,387 Members | 1,365 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,387 software developers and data experts.

'ref' question


public class stringtemp
{
String k ;
public stringtemp(ref String inp)
{
k = inp ;
}
public void Change()
{
k = k.Remove(0, 1) ;
}
};

String stringtochange = new String("Hello".ToCharArray()) ;
stringtemp t = new stringtemp(ref stringtochange) ;
t.Change() ;

Why isnt stringtochange changed to 'ello' here? When I try a similar sample
with an ArrayList instead of a String, my original variable gets reflected.
So my question is: How can i make sure i am operating on a reference?
Documentation says all class types are passed by references. Could someone
elaborate?

TIA


Nov 17 '05 #1
12 1341
mdb
"Priyesh" <pr*****@donotreply.com> wrote in
news:uf**************@TK2MSFTNGP15.phx.gbl:
Why isnt stringtochange changed to 'ello' here? When I try a similar
sample with an ArrayList instead of a String, my original variable
gets reflected. So my question is: How can i make sure i am operating
on a reference? Documentation says all class types are passed by
references. Could someone elaborate?


The "string" class isn't a reference type - its a value type, so in:

public stringtemp(ref String inp)
{
k = inp ;
}

even though you are ref'fing inp, the 'k=inp' is still done as a value
assignment.

In order to do what you want, you'll have to put the 'string inp' as a
member of another class, and pass the class instance instead of the string
itself.

--
-mdb
Nov 17 '05 #2
public stringtemp(ref String inp)

says that you can change "inp" _in the constructor_ and the
corresponding argument variable will change on the outside.

String k;

says what? Does it say "k is a reference to a string"? No, it says, "k
is a string". So, when you say

this.k = inp;

what you're saying is, "k should be the same string as is contained in
inp*". Since you never avail yourself of the opportunity to change inp
_within the constructor_, you just change k, but never inp,
"stringtochange" is never changed.

Just because you declare a parameter as "ref" does not mean that its
"refness" is sticky and follows that string value wherever it goes.
Now, if C# were allow you to say something like:

public class stringtemp
{
ref String k;

public stringtemp(ref String inp)
{
this.k = inp;
}
...
}

then we might have something going here. However "ref String k" is not
a valid field declaration, so you're out of luck.

By the time you get to the Change method, the fact that "inp" was
originally declared "ref" is completely irrelevant. It's only relevant
within the constructor.

One of the design goals of C# and .NET was to avoid the kind of pointer
mayhem that can occur in C and C++. That's why you can't declare
variables that hold references: they would just be pointers under
another name, and open the door to all kinds of madness. Take another
look at your example, and think of it like this:

String stringtochange = "Hello";
stringtemp t = new stringtemp(ref stringtochange) ;
... 200 lines of complex code here ...
t.Change() ;

suddenly, without any warning or any indication in the code that it
might happen, the variable "stringtochange" *magically* changes after
the call to t.Change(). How easy is it to maintain that code? This is
exactly what C# seeks to avoid.
* Technically, this is a bit of a lie. k is, in fact, a reference to a
string, since strings are held by reference in string variables.
However, "inp" is a reference to a reference to a string, which is what
you need in order to change the argument passed in on the call.
Correctly, I should have said that there is no way in C# to declare k
as a private member that is a reference to a reference to a string,
which is what you would need in order to create the behaviour you want
to see. However, I rephrased it all in order to avoid confusion. In
this case you can think of strings as values, even though they're
really references. For the purposes of this explanation the distinction
is irrelevant.

Nov 17 '05 #3
Not so. Strings are indeed a reference type. After all, System.String is a
class, not a struct. However, because strings are immutable, they have very
value-like semantics, because any change to a string results in a completely
new string being created "under the hood". In most situations this makes a
string "behave" superficially as if it were a value type. For example:

myString = "foo" + someOtherString;

.... really results in the compiler emitting code that works more like this:

myString = new String("foo" + someOtherString)

.... which will not change the original myString reference if it exists in
the caller's context, which makes this *appear* to behave like a value type.
But, all that is passed into a conventional string parameter of a method is
a *reference* to a string, nonetheless.

--Bob

----- Original Message -----
From: "mdb" <m_b_r_a_y@c_t_i_u_s_a__d0t__com>
Newsgroups: microsoft.public.dotnet.languages.csharp
Sent: Wednesday, June 01, 2005 4:09 PM
Subject: Re: 'ref' question

The "string" class isn't a reference type - its a value type, so in:

Nov 17 '05 #4
try rewriting it because the way it was you never actually accesing inp parameter.

public class stringtemp
{
public stringtemp()
{
}
public void Change(ref String inp)
{
inp.Remove(0, 1) ;
}
};
"Priyesh" <pr*****@donotreply.com> wrote in message news:<uf**************@TK2MSFTNGP15.phx.gbl>...
public class stringtemp
{
String k ;
public stringtemp(ref String inp)
{
k = inp ;
}
public void Change()
{
k = k.Remove(0, 1) ;
}
};

String stringtochange = new String("Hello".ToCharArray()) ;
stringtemp t = new stringtemp(ref stringtochange) ;
t.Change() ;

Why isnt stringtochange changed to 'ello' here? When I try a similar sample
with an ArrayList instead of a String, my original variable gets reflected.
So my question is: How can i make sure i am operating on a reference?
Documentation says all class types are passed by references. Could someone
elaborate?

TIA

Nov 17 '05 #5
Bruce,

Thanks for the reply.

Couple of points that i dont understand still.
String stringtochange = "Hello";
stringtemp t = new stringtemp(ref stringtochange) ;
... 200 lines of complex code here ...
t.Change() ;

suddenly, without any warning or any indication in the code that it
might happen, the variable "stringtochange" *magically* changes after
the call to t.Change(). How easy is it to maintain that code? This is
exactly what C# seeks to avoid.
This does not hold good when i use an ArrayList or another user defined
class. My original variable is *magically*
changed.(See example below) I am failing to draw a common reference
behaviour i can base on from all these.
Correctly, I should have said that there is no way in C# to declare k
as a private member that is a reference to a reference to a string,
I think you are right here when using a string. When i use an ArrayList it
seem to work.

Here's what i tried.

public class arraylistchange
{
ArrayList ar ;

//This is passed in as a reference even if i dont specify ref.
public arraylistchange(ArrayList arIn)
{
//This seems to be copied as a reference. So my member
//variable ar is a reference type even if i dont specify it to be?
ar = arIn ;
}
public void Change()
{
ar.Add("456") ;
}
};

ArrayList ar = new ArrayList(10) ;
ar.Add("123") ;
arraylistchange archange = new arraylistchange(ar) ;
archange.Change() ;
int n = ar.Count ;//is 2

I thought String would do the same thing, but didnt. Any explanation about
this which would help me understand this better would be really helpful.
Thanks for your time.

"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com... public stringtemp(ref String inp)

says that you can change "inp" _in the constructor_ and the
corresponding argument variable will change on the outside.

String k;

says what? Does it say "k is a reference to a string"? No, it says, "k
is a string". So, when you say

this.k = inp;

what you're saying is, "k should be the same string as is contained in
inp*". Since you never avail yourself of the opportunity to change inp
_within the constructor_, you just change k, but never inp,
"stringtochange" is never changed.

Just because you declare a parameter as "ref" does not mean that its
"refness" is sticky and follows that string value wherever it goes.
Now, if C# were allow you to say something like:

public class stringtemp
{
ref String k;

public stringtemp(ref String inp)
{
this.k = inp;
}
...
}

then we might have something going here. However "ref String k" is not
a valid field declaration, so you're out of luck.

By the time you get to the Change method, the fact that "inp" was
originally declared "ref" is completely irrelevant. It's only relevant
within the constructor.

One of the design goals of C# and .NET was to avoid the kind of pointer
mayhem that can occur in C and C++. That's why you can't declare
variables that hold references: they would just be pointers under
another name, and open the door to all kinds of madness. Take another
look at your example, and think of it like this:

String stringtochange = "Hello";
stringtemp t = new stringtemp(ref stringtochange) ;
... 200 lines of complex code here ...
t.Change() ;

suddenly, without any warning or any indication in the code that it
might happen, the variable "stringtochange" *magically* changes after
the call to t.Change(). How easy is it to maintain that code? This is
exactly what C# seeks to avoid.
* Technically, this is a bit of a lie. k is, in fact, a reference to a
string, since strings are held by reference in string variables.
However, "inp" is a reference to a reference to a string, which is what
you need in order to change the argument passed in on the call.
Correctly, I should have said that there is no way in C# to declare k
as a private member that is a reference to a reference to a string,
which is what you would need in order to create the behaviour you want
to see. However, I rephrased it all in order to avoid confusion. In
this case you can think of strings as values, even though they're
really references. For the purposes of this explanation the distinction
is irrelevant.

Nov 17 '05 #6
Amar,

Thanks for the reply. The point i was trying to put forward is elaborated in
my reply to Bruce.
"Amar" <ma******@gmail.com> wrote in message
news:8a**************************@posting.google.c om...
try rewriting it because the way it was you never actually accesing inp
parameter.

public class stringtemp
{
public stringtemp()
{
}
public void Change(ref String inp)
{
inp.Remove(0, 1) ;
}
};
"Priyesh" <pr*****@donotreply.com> wrote in message
news:<uf**************@TK2MSFTNGP15.phx.gbl>...
public class stringtemp
{
String k ;
public stringtemp(ref String inp)
{
k = inp ;
}
public void Change()
{
k = k.Remove(0, 1) ;
}
};

String stringtochange = new String("Hello".ToCharArray()) ;
stringtemp t = new stringtemp(ref stringtochange) ;
t.Change() ;

Why isnt stringtochange changed to 'ello' here? When I try a similar
sample
with an ArrayList instead of a String, my original variable gets
reflected.
So my question is: How can i make sure i am operating on a reference?
Documentation says all class types are passed by references. Could
someone
elaborate?

TIA

Nov 17 '05 #7
Priyesh <pr*****@donotreply.com> wrote:
This does not hold good when i use an ArrayList or another user defined
class. My original variable is *magically*
changed.
That's because ArrayList is mutable, while String isn't.

Consider:

1 {
2 string original = "foo";
3 string copy = original;
4
5 copy = "bar";
6 }

After the assignment in line three, both original and copy reference the
same string. However, after line five, copy now references a new string.

Replace line five with (from your example)

copy = original.Remove(0, 1)

and you get the same situation: copy now references a whole new string.

This happens because strings are immutable (their state cannot be changed).

The same thing happens here, for example:

myString = myString.Replace("foo", "bar");

After this, myString now references a whole new string which looks like the
old one but has all occurences of "foo" replaced with "bar".
//This is passed in as a reference even if i dont specify ref.
public arraylistchange(ArrayList arIn)


Note that this is a mistake -- if that parameter were of type string, a
reference would be passed just the same. The only difference here is that
strings are immutable, while ArrayLists aren't.

Also, a 'ref' parameter is different from a reference type parameter. See
<http://www.yoda.arachsys.com/csharp/parameters.html>.
Nov 17 '05 #8
Amar <ma******@gmail.com> wrote:
try rewriting it because the way it was you never actually accesing inp parameter.

public class stringtemp
{
public stringtemp()
{
}
public void Change(ref String inp)
{
inp.Remove(0, 1) ;
}
};


That won't change the value either. You'd need:

inp = inp.Remove (0, 1);

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9
Priyesh <pr*****@donotreply.com> wrote:
String stringtochange = "Hello";
stringtemp t = new stringtemp(ref stringtochange) ;
... 200 lines of complex code here ...
t.Change() ;

suddenly, without any warning or any indication in the code that it
might happen, the variable "stringtochange" *magically* changes after
the call to t.Change(). How easy is it to maintain that code? This is
exactly what C# seeks to avoid.


This does not hold good when i use an ArrayList or another user defined
class. My original variable is *magically*
changed.(See example below) I am failing to draw a common reference
behaviour i can base on from all these.


The value of your variable isn't changed at all. The value of your
variable is a reference to an object. The reference doesn't change, but
the ArrayList it refers to does. Now, that can't happen with a string,
because strings are immutable. None of the methods you can call on a
string actually change its contents.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10
The two replies you already received are correct. Here is another way
of phrasing it.

You are, in a way, comparing apples and oranges. The case of ArrayList
and String are identical. You have the same capabilities and the same
thing is happening, but you're failing to see a distinction.

The distinction is this: when you pass an ArrayList, you can _change
the ArrayList_, but you _can't_ change _which ArrayList_ "ar" points
to. "ar" still points to the _same ArrayList as before_. It's just that
you've change _what_ that particular ArrayList _contains_.

If you try to write the code so that you try to change _which
ArrayList_ ar points to, you'll find that you can't:

public class arraylistchange
{
ArrayList ar ;

//This is passed in as a reference even if i dont specify ref.
// (So is a string, by the way.)
public arraylistchange(ArrayList arIn)
{
//This seems to be copied as a reference. So my member
//variable ar is a reference type even if i dont specify it to be?
// (The string variable was a reference type, too.)
ar = arIn ;
}
public void Change()
{
// Here we create a whole new ArrayList and change what
// this.ar points to.
ArrayList newOne = new ArrayList();
newOne.Add("123");
newOne.Add("456");
this.ar = newOne;
}
};

ArrayList ar = new ArrayList(10) ;
ar.Add("123") ;
arraylistchange archange = new arraylistchange(ar) ;
archange.Change() ;
int n = ar.Count ;//is *1*, because it still points to the original
ArrayList, not the new one

See? You can change the ArrayList itself, but if you change _which
ArrayList_ the field this.ar points to, the variable ar on the outside
doesn't change. It can't, because C# doesn't allow references to
references.

This is what is happening with strings. As C# Learner pointed out,
strings are immutable. In your string Change() method, you didn't say:

this.k.SetNewStringValue("Hello");

or something like that. You didn't _change the value of the string_.
You instead _changed which string_ this.k pointed to, because C# won't
let you change the values of strings, only create new ones and point
variables to the new string.

So, what you were doing in the two methods was different.

That's why I said that Strings, because of the way they're implemented
in C#, sort of act like value types. You can't point x to a string and
y to a string then "change the string" so that it changes in x and y,
because in C# you can't change strings. You can only change x to point
to a different string, which of course doesn't affect y at all.

ArrayLists and other reference types are different. You can change an
ArrayList: add items, remove items, etc. If x and y point to the same
ArrayList, and you change that ArrayList, both x and y will now point
to the changed ArrayList. However, as for strings, if you point x and y
to the same ArrayList and then create a new ArrayList and point x to
that, y remains unaffected.

Does that help? :)

Nov 17 '05 #11
Bruce.

Defenitely helps. Thanks for your time.

"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
The two replies you already received are correct. Here is another way
of phrasing it.

You are, in a way, comparing apples and oranges. The case of ArrayList
and String are identical. You have the same capabilities and the same
thing is happening, but you're failing to see a distinction.

The distinction is this: when you pass an ArrayList, you can _change
the ArrayList_, but you _can't_ change _which ArrayList_ "ar" points
to. "ar" still points to the _same ArrayList as before_. It's just that
you've change _what_ that particular ArrayList _contains_.

If you try to write the code so that you try to change _which
ArrayList_ ar points to, you'll find that you can't:

public class arraylistchange
{
ArrayList ar ;

//This is passed in as a reference even if i dont specify ref.
// (So is a string, by the way.)
public arraylistchange(ArrayList arIn)
{
//This seems to be copied as a reference. So my member
//variable ar is a reference type even if i dont specify it to be?
// (The string variable was a reference type, too.)
ar = arIn ;
}
public void Change()
{
// Here we create a whole new ArrayList and change what
// this.ar points to.
ArrayList newOne = new ArrayList();
newOne.Add("123");
newOne.Add("456");
this.ar = newOne;
}
};

ArrayList ar = new ArrayList(10) ;
ar.Add("123") ;
arraylistchange archange = new arraylistchange(ar) ;
archange.Change() ;
int n = ar.Count ;//is *1*, because it still points to the original
ArrayList, not the new one

See? You can change the ArrayList itself, but if you change _which
ArrayList_ the field this.ar points to, the variable ar on the outside
doesn't change. It can't, because C# doesn't allow references to
references.

This is what is happening with strings. As C# Learner pointed out,
strings are immutable. In your string Change() method, you didn't say:

this.k.SetNewStringValue("Hello");

or something like that. You didn't _change the value of the string_.
You instead _changed which string_ this.k pointed to, because C# won't
let you change the values of strings, only create new ones and point
variables to the new string.

So, what you were doing in the two methods was different.

That's why I said that Strings, because of the way they're implemented
in C#, sort of act like value types. You can't point x to a string and
y to a string then "change the string" so that it changes in x and y,
because in C# you can't change strings. You can only change x to point
to a different string, which of course doesn't affect y at all.

ArrayLists and other reference types are different. You can change an
ArrayList: add items, remove items, etc. If x and y point to the same
ArrayList, and you change that ArrayList, both x and y will now point
to the changed ArrayList. However, as for strings, if you point x and y
to the same ArrayList and then create a new ArrayList and point x to
that, y remains unaffected.

Does that help? :)

Nov 17 '05 #12
Thanks.

"C# Learner" <cs****@learner.here> wrote in message
news:1l***************@csharp.learner...
Priyesh <pr*****@donotreply.com> wrote:
This does not hold good when i use an ArrayList or another user defined
class. My original variable is *magically*
changed.


That's because ArrayList is mutable, while String isn't.

Consider:

1 {
2 string original = "foo";
3 string copy = original;
4
5 copy = "bar";
6 }

After the assignment in line three, both original and copy reference the
same string. However, after line five, copy now references a new string.

Replace line five with (from your example)

copy = original.Remove(0, 1)

and you get the same situation: copy now references a whole new string.

This happens because strings are immutable (their state cannot be
changed).

The same thing happens here, for example:

myString = myString.Replace("foo", "bar");

After this, myString now references a whole new string which looks like
the
old one but has all occurences of "foo" replaced with "bar".
//This is passed in as a reference even if i dont specify ref.
public arraylistchange(ArrayList arIn)


Note that this is a mistake -- if that parameter were of type string, a
reference would be passed just the same. The only difference here is that
strings are immutable, while ArrayLists aren't.

Also, a 'ref' parameter is different from a reference type parameter. See
<http://www.yoda.arachsys.com/csharp/parameters.html>.

Nov 17 '05 #13

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

Similar topics

12
by: Ori | last post by:
Hi, I have a simple question. Let say that i have 3 functions as following private main() { Object oTop = new Object(); }
2
by: Flip | last post by:
Maybe I'm reading too much, I'm sorry if this is a very newbie question. I'm reading the OReilly's Programming C# book, and it talks about ref and out, cool. I thought I understood you have out...
6
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...
7
by: Simon Cheng | last post by:
Hi, Does MC++ support out/ref param semantics (as C# does)? The MC++ spec doesn't mention about this, so supposedly they are not supported? Thanks, Simon
2
by: Tim Reynolds | last post by:
Team, We need some guidance here. We are developing a web service to expose to external system. We are not sure which is the best path to take. We have multiple input fields required and a few...
3
by: Pratcp | last post by:
Hello, I have an asp.net Web app in vb.net trying to call a C# web service which takes a reference parameter. I tried a simple C# web app to call the Web service and it works perfectly. However,...
4
by: Deckarep | last post by:
Hello fellow C# programmers, This question is more about general practice and convention so here goes: I got into a discussion with a co-worker who insisted that as a general practice all...
4
by: colin | last post by:
How can I access a field contained in fieldInfo by reference so I can pass it to a function ? ive tried __refvalue but this needs a type known at compile time, I can access it with SetValue and...
65
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...

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.