Click here to Skip to main content
15,924,193 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
MIDL
String ip = new String("str".ToCharArray());
            String p = ip;
            p = "newstr";
            Console.WriteLine(ip);



Output is: str

As it is written in book that

Reference types:
Reference types are allocated on heap and are garbage collected when they are no longer being used. They are created using new operator, and there is no delete operator for these types unlike C++ where user has to explicitly delete the types created using delete operator. In C#, they are automatically collected by garbage collector.
Reference types include:
• Classes
• Interfaces
• Collection types like Arrays
• String


but the op of above program does not satisfy this.
Posted
Comments
Sergey Alexandrovich Kryukov 4-Feb-11 1:41am    
Good question...
--SA

Great, you know the reference type! Now System.String is what? This is class, right. So... Read you own text. All correct.

This question is interesting. Thank you.

But the string is very special class. It's the reference type, but assignment operator is defined so it logically behaves pretty much like a value type. In fact, this is imitation of value semantic. Same thing with the operator "==". It is not your default comparison of instances of classes. Strings compare "semantically" not referentially. To see the difference, compare strings using object.ReferenceEquals. Objects can be different, referential identity different, but comparison returns true.

There are many good reasons to imitate value semantics in string, as well as making them classes. This has something to do with memory economy and non-mutable nature of strings while keeping intuitive semantic.

The essence of string design can be understood if you learn string interning: http://msdn.microsoft.com/en-us/library/system.string.intern.aspx[^].

—SA
 
Share this answer
 
v2
Comments
Sandeep Mewara 4-Feb-11 5:27am    
Good answer! 5+
Sergey Alexandrovich Kryukov 13-Feb-12 16:39pm    
Thank you, Sandeep.
--SA
Espen Harlinn 4-Feb-11 11:43am    
Good answer 5+
Sergey Alexandrovich Kryukov 13-Feb-12 16:39pm    
Thank you, Espen.
--SA
Strings are also immutable - see here[^] for an explanation.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 4-Feb-11 5:40am    
Thank you Abhinav, but I already mentioned that in first place of my answer, last paragraphs.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900