开发者

why string behaves as value type even though it is a reference type in c# [duplicate]

开发者 https://www.devze.com 2023-03-28 23:27 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: In C#, why is String 开发者_运维百科a reference type that behaves like a value type?
This question already has answers here: Closed 11 years ago.

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.


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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号