Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top