473,788 Members | 2,733 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

'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
12 1361
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.SetNewSt ringValue("Hell o");

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*******@cana da.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.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.SetNewSt ringValue("Hell o");

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*****@donotr eply.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.Replac e("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.arachs ys.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
1465
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
1633
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 on the outgoing and ref on the accepting method side. But now I'm reading a webpage from another posting (http://www.yoda.arachsys.com/csharp/parameters.html), that has the out (or ref) on the method call and on the method declaration. HUH? I...
6
2849
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 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...
7
3831
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
1971
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 output fields. We are thinking to either 1) Make all input fields one class and have one parameter for our web service of this object type and make all output fields a second class and have return type of our web method return an object of this...
3
4070
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, when I try it in the vb.net web app, I run into XML definition errors. Looks like the proxy class is not able to generate the correct XML with the ref parameter. Here is error: The element 'urn:test-com:document:test:rfc:functions:T_RETURN has
4
2815
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 objects should be passed by reference using the ref keyword generally speaking because as the writer of code you are conveying your intentions that an Object should/can be modified by your function.
4
1481
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 GetValue but in one case where the field is a structure I need to pass it as a ref to a function. as it is a structure i cant make a 'new' copy and pass that as a ref and then copy it back.
65
3929
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
10370
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
10177
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
10113
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
9969
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
7519
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
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4074
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
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2896
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.