3

Possible Duplicate:
In C#, why is String a reference type that behaves like a value type?

I know string is a reference type since string can be very large and stack is only 1 mb . But programatically while coding i see it behaves like value type for eg

string func_name(string streg)

{    
streg="hello";

return streg; 

}

-------------

string str="hi";

str= func_name(str);

now str gets the value hello ?

why so ? it bahaves exactly like value type here.

Community
  • 1
  • 1
Kuntady Nithesh
  • 11,371
  • 20
  • 63
  • 86
  • How is this acting like a value type? A reference type would have the same behaviour in this test. – dlev Aug 16 '11 at 14:39

3 Answers3

2

Because it was decided that the string type would be immutable, but strings can still be very large.

You can read why here:

Why .NET String is immutable?

And another question similar to yours:

In C#, why is String a reference type that behaves like a value type?

Community
  • 1
  • 1
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
0

It's because it's an immutable type - i.e. you can't change the contents of the object once it's been defined. Jon Skeet gives a pretty good explanation of this concept in relation to the string type here

John Sibly
  • 22,782
  • 7
  • 63
  • 80
0

It is because strings are immutable

Consider the example

string a ="Hello"; a=a+"World";

Eventhough the second line seems like we are modifying the contents of it ,it is not

The CLR will create a new string object with the value Hello world and copies the reference of this new object back to the variable a. The type is immutable but the variable is not.You can always assign a new reference to the variable of type string

Ashley John
  • 2,379
  • 2
  • 21
  • 36