473,480 Members | 1,874 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Basic Question: string reference type

Hello all,

In C# string is a reference type but I learned that string is different from
other reference types such as class. For example, if you pass a string
argument to a method and then change the value in that method the
modification will not be visible outside the method. However this is not
true for classes. In my example I am not using ref keyword.

Thanks for feedback.
Nov 15 '05 #1
8 5028
Correct, the terminology used is that strings are immutable reference types.
So they don't behave quite like other reference types. Once defined, a
string cannot change value. However, a variable holding a reference to a
string may certainly be assigned a new string object. This is often
encountered in the following:

string mystr = "Good morning.";
mystr.Replace ("morning", "evening"); // does nothing
mystr = mystr.Replace ("morning", "evening"); // expected behavior

Not really about strings in particular, but here's some good references on
reference / value types if you want more info:

http://www.pobox.com/~skeet/csharp/parameters.html
http://www.pobox.com/~skeet/csharp/memory.html
and
http://www.mag37.com/csharp/articles...enceTypes.html
(by your's truly)

--
Mike Mayer
http://www.mag37.com/csharp/
mi**@mag37.com
"Nader" <na**********@hotmail.com> wrote in message
news:eY****************@TK2MSFTNGP11.phx.gbl...
Hello all,

In C# string is a reference type but I learned that string is different from other reference types such as class. For example, if you pass a string
argument to a method and then change the value in that method the
modification will not be visible outside the method. However this is not
true for classes. In my example I am not using ref keyword.

Thanks for feedback.

Nov 15 '05 #2
Thanks Mike,

I was just wondering what is happening behind the scenes that make strings
act differently.
Nov 15 '05 #3
"Nader" <na**********@hotmail.com> wrote in message
news:eu**************@tk2msftngp13.phx.gbl...
Thanks Mike,

I was just wondering what is happening behind the scenes that make strings
act differently.


I don't think there's really much "beind the scenes" magic. There is no
method that allows you to change a string, therefore it is immutable. You
can make your own class that is immutable pretty easily:

(pardon this code, it's all written on the fly in the newsreader, so there
are surely some grammatical mistakes)

public sealed class ImmutableComplexNumber {
public ImmutableComplexNumber (double real, double imag) {
this.real = real;
this.imag = imag;
}
double real;
double imag;

public double AbsoluteValue {
get { return (real * real) + (imag * imag); }
}

public ImmutableComplexNumber Add (ImmutableComplexNumber x) {
return new ImmutableComplexNumber (this.real + x.real, this.imag +
x.imag);
}
}

There is no way for a user to actually change the value of an instance of
ImmutableComplexNumber once the've created it. Even add will simply return a
new number. The class is sealed, real and imag are private, and there are no
publicly accesible methods (other than the constructor) that will change
those two private fields. Pretty much the same for strings.

Now strings have the additional benefit of being known by the CLR so it can
do cool tricks like string interning and other optimizations. Here's an
article I've run across in the past that has some details on inner workings
of the string class.

http://www.wintellect.com/resources/...2/Jan2002.aspx
http://www.codeproject.com/dotnet/strings.asp

Hope that answers your questions.

--
Mike Mayer
http://www.mag37.com/csharp/
mi**@mag37.com

Nov 15 '05 #4
Nader <na**********@hotmail.com> wrote:
In C# string is a reference type but I learned that string is different from
other reference types such as class.
No it's not. Not really.
For example, if you pass a string
argument to a method and then change the value in that method the
modification will not be visible outside the method.
Changing the value of a reference variable does *not* make any change
in the object itself.
However this is not true for classes.


Yes it is.

Here's an example of what I think you mean:

using System;

public class Test
{
static void Main()
{
string x = "hello";
Foo (x);
Console.WriteLine (x);
}

static void Foo(string y)
{
y = "world";
}
}

The above prints hello, but you'd expect it to print world. Now, that's
exactly the same as:
public class Test
{
static void Main()
{
ArrayList al = new ArrayList();
al.Add ("hello");
Foo (al);
Console.WriteLine (al[0]);
}

static void Foo(ArrayList y)
{
y = new ArrayList();
y.Add ("world");
}
}

Note that we're changing the *value of y* in both cases, not the data
within the object that the original reference points to.

Strings are absolutely reference types - but you need to be clear about
the difference between changing which object a variable's value refers
to and changing the *contents* of the object a variable's value refers
to.

See http://www.pobox.com/~skeet/csharp/parameters.html and
http://www.pobox.com/~skeet/csharp/memory.html for more details.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5
Michael Mayer <mi**@mag37.com> wrote:
Correct, the terminology used is that strings are immutable reference types.
So they don't behave quite like other reference types.


They do! They behave exactly like other reference types. It so happens
that you can't change them, but that's in common with a lot of other
reference types, and it's not "special" at all - it's not like there's
another rule to learn, it's just applying the normal rules.

The only "tricky" thing about strings is string literals - and they're
just references to string objects which will exist by the time you use
the literal, and are interned so that the same literal will always
refer to the same instance within an application.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6
Please look at the piece of code below.

Even though my argument list in test(...) method does not include ref
keyword the result is visible in the Main() function and you get "Hello from
testClass".

This is not the case when I replace myString class with a simple string.

using System;

class myString
{
public myString()
{
str1 = "Hello from myString";
}
public string str1;
}

class testClass
{
public void test(myString astr)
{
astr.str1 = "Hello from testClass";
}
}

class theApp
{
public static void Main()
{
testClass tc = new testClass();
myString ms = new myString();
tc.test(ms);
Console.WriteLine("{0}", ms.str1);
}
}


Nov 15 '05 #7
Your class myString is NOT an immutable class (the way string is) since you
made str1 a public field of class myString (see my previous post with the
complex number example - this would be an immutable class).

I would suspect that if you had read those articles that Jon and I wrote
(posted previously) they will clear up some of your mis-understanding. I'll
try here briefly, but I must insist that you go read Jon's or my articles (I
think mine is more geared toward a beginner to C#, while Jon's uses more
accurate, technical verbage).

However, we can rewrite your example below to do the same thing as you
mentioned in your first post:

public void test(myString astr)
{
astr = new myString ("Hello from testClass";)
}

Note that here in my version of test, I am trying to change the VALUE of
astr (which is a reference to a class). Since astr is passed by value, this
has no affect in the calling function. This is what you mentioned doing in
your first post - changing a string in a method, probably as follows:

public void testOP (string mystring)
{
mystring = "new string";
}

In your version (below) you are not changing the value of astr, but rather,
the value of str1 in an instance of myString class. Since both testClass and
theApp reference that same instance, you will see the change both places.

Another note, you might find the following useful on naming conventions, it
will make your code more immediately readable by others (that is, classes
and methods should be capitalized in C#)
http://msdn.microsoft.com/library/de...guidelines.asp
--
Mike Mayer
http://www.mag37.com/csharp/
mi**@mag37.com

"Nader" <na**********@hotmail.com> wrote in message
news:ei**************@TK2MSFTNGP11.phx.gbl...
Please look at the piece of code below.

Even though my argument list in test(...) method does not include ref
keyword the result is visible in the Main() function and you get "Hello fr om testClass".

This is not the case when I replace myString class with a simple string.

using System;

class myString
{
public myString()
{
str1 = "Hello from myString";
}
public string str1;
}

class testClass
{
public void test(myString astr)
{
astr.str1 = "Hello from testClass";
}
}

class theApp
{
public static void Main()
{
testClass tc = new testClass();
myString ms = new myString();
tc.test(ms);
Console.WriteLine("{0}", ms.str1);
}
}

Nov 15 '05 #8
"Jon Skeet" <sk***@pobox.com> wrote in message
news:MP************************@news.microsoft.com ...
Michael Mayer <mi**@mag37.com> wrote:
Correct, the terminology used is that strings are immutable reference types. So they don't behave quite like other reference types.


They do! They behave exactly like other reference types. It so happens
that you can't change them, but that's in common with a lot of other
reference types, and it's not "special" at all - it's not like there's
another rule to learn, it's just applying the normal rules.


Jon,
My first post didn't say exactly what I meant for it to have said. I think
my second post clarified what I meant a little better.

I was trying to get across something you mentioned on one of your pages:

"Note that many types (such as string) appear in some ways to be value
types, but in fact are reference types. These are known as immutable types."

I should have mentioned that they still follow all the rules of reference
types, with the added benefit that, like value types, you don't have to
worry about them changing when passed as parameters to other methods.
--
Mike Mayer
http://www.mag37.com/csharp/
mi**@mag37.com

Nov 15 '05 #9

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

Similar topics

4
1704
by: Ryan Gaffuri | last post by:
I know that this works. I just don't get the syntax. I know its checking the OS. just not sure how it works. var v = navigator.appVersion.toUpperCase() if (1+v.indexOf('WIN98') os =...
1
1320
by: Oliver | last post by:
I'm an expert C# programmer (honest) but... the following code prints 'Oranges', not 'ORANGES' - this confuses me because I thought reference types (eg string) where passed by...err..reference -...
13
2274
by: gmccallum | last post by:
General Info: A struct is stored on the stack and a class on the heap. A struct is a value type while a class is a reference type. Question: What if a struct contains a string...
14
2481
by: luis | last post by:
Are basic types (int, long, ...) objetcs or not? I read that in C# all are objects including basic types, derived from Object class. Then in msdn documentation says that boxing converts basic...
13
15521
by: Pete | last post by:
I'm cross posting from mscom.webservices.general as I have received no answer there: There has been a number of recent posts requesting how to satisfactorily enable BASIC authorization at the...
3
2028
by: Simon Hart | last post by:
Hi, I am trying to implement some functionality as seen in MS CRM 3.0 whereby a basic Xml is deserialized into an object which contains properties. What I want to do from here is; cast the basic...
35
1861
by: rebeccatre | last post by:
hi can Variant archiving setTimout('.. capability be done without using it? :-)
20
4000
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This...
8
2183
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
0
7046
marktang
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,...
0
7088
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...
1
6741
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...
0
6956
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...
0
5342
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4783
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...
0
4485
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
2986
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1300
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 ...

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.