'ref' question

  • Thread starter Thread starter Priyesh
  • Start date Start date
P

Priyesh

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
 
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.
 
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.
 
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
 
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) ;
}
};
 
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.
 
Amar,

Thanks for the reply. The point i was trying to put forward is elaborated in
my reply to Bruce.
 
Priyesh said:
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>.
 
Amar said:
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);
 
Priyesh said:
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.
 
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? :)
 
Bruce.

Defenitely helps. Thanks for your time.

Bruce Wood said:
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? :)
 
Thanks.

C# Learner said:
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".


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>.
 
Back
Top