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 12 1360
"Priyesh" <pr*****@donotr eply.com> wrote in
news:uf******** ******@TK2MSFTN GP15.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
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__c om>
Newsgroups: microsoft.publi c.dotnet.langua ges.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:
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*****@donotr eply.com> wrote in message news:<uf******* *******@TK2MSFT NGP15.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
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*******@cana da.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.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.
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.goo gle.com... 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*****@donotr eply.com> wrote in message news:<uf******* *******@TK2MSFT NGP15.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
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 >.
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.co m> http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Priyesh <pr*****@donotr eply.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.co m> http://www.pobox.com/~skeet
If replying to the group, please do not mail me too This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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();
}
|
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...
|
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...
|
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
|
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...
| |
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
|
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.
|
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.
|
by: Arjen |
last post by:
Hi,
Form a performance perspective, is it wise to use the ref statement as much
as possible?
Thanks!
Arjen
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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,...
| |
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...
|
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...
|
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,...
|
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...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |