473,761 Members | 2,410 Online
Bytes | Software Development & Data Engineering Community
+ 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 5043
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**********@h otmail.com> wrote in message
news:eY******** ********@TK2MSF TNGP11.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**********@h otmail.com> wrote in message
news:eu******** ******@tk2msftn gp13.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 ImmutableComple xNumber {
public ImmutableComple xNumber (double real, double imag) {
this.real = real;
this.imag = imag;
}
double real;
double imag;

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

public ImmutableComple xNumber Add (ImmutableCompl exNumber x) {
return new ImmutableComple xNumber (this.real + x.real, this.imag +
x.imag);
}
}

There is no way for a user to actually change the value of an instance of
ImmutableComple xNumber 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**********@h otmail.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.WriteLi ne (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.WriteLi ne (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.co m>
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.co m>
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.WriteLi ne("{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**********@h otmail.com> wrote in message
news:ei******** ******@TK2MSFTN GP11.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.WriteLi ne("{0}", ms.str1);
}
}

Nov 15 '05 #8
"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@news.microsof t.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
1724
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 = 'Win98'; else if (1+v.indexOf('WINNT') os = 'WinnT';
1
1340
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 - so changing where the reference points to in a method ought to change the behaviour outside the method. ....using the 'ref' keyword makes this happen. it's almost as if references passed to methods are *copied*.
13
2314
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 property(variable). The string would be a reference type being contained in a value type. Would this filter up and cause the stack to now be a reference type placed on the heap or would it still be on the stack with a pointer used internally to point to a...
14
2511
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 types in objects. But if they are objects why it´s need this conversion? Aren´t objects (basic types) like Java?
13
15565
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 HTTP level but as yet no fully useful answer. I too have been trying to call an apache/axis webservice which desires a username/password from my C# Client. (ie the equivalent of _call.setUsername("Myname") name from within a Java client proxy)...
3
2050
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 object into a more strongly typed class which knows what properties to expect. The basic top level class is as follows: using System;
35
1924
by: rebeccatre | last post by:
hi can Variant archiving setTimout('.. capability be done without using it? :-)
20
4042
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 tells me if a variable has changed, give me the original and current value, and whether the current value and original value is/was null or not. This one works fine but is recreating the same methods over and over for each variable type. ...
8
2219
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
9538
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, 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...
0
9353
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,...
0
9975
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
9909
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,...
1
7342
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
6623
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5241
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...
0
5384
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3481
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.