Why (object) s1! =(object) s2? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
7th Feb 2018, 6:04 AM
Garry Evmenchik
Garry Evmenchik - avatar
4 Answers
+ 7
Because they do not have the same reference, they are not the same object. When you modify one, the other one is not modified
7th Feb 2018, 6:10 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 7
@~swim~: This is an excellent follow up the original question posted by Garry! The short answer is due to a compiler optimization and the string intern pool. -------------------------------- - Compiler Optimization: -------------------------------- The first thing to understand is string literals using the + operator are already concatenated at compile time when the code is converted to IL (Intermediate Language). Therefore, the following lines of code: var strA = "abcdef"; var strB = "abc" + "def"; var strC = "abcd" + "ef"; var strD = "ab" + "cdef"; var strE = "ab" + "cd" + "ef"; var strF = "a" + "b" + "c" + "d" + "e" + "f"; May as well as have been written as: var strA = "abcdef"; var strB = "abcdef"; var strC = "abcdef"; var strD = "abcdef"; var strE = "abcdef"; var strF = "abcdef"; -------------------------------- - String Intern Pool: -------------------------------- The second thing to understand is, in .NET, all string literals are created once in memory, which is made possible using the String Intern Pool as described in the excerpt below: "String Intern Pool is a special table allocated on Large Object Heap which maintains references of all strings that are created on a program. CLR keeps track of those strings that are created in memory and uses it when it needs to create the same string again. This ensures that new memory is not used whenever the content of the string is not different." - The above quote was taken from the following link, which is an excellent article on the String Intern Pool in .NET: - http://dailydotnettips.com/2012/02/12/the-string-intern-pool/
8th Feb 2018, 4:59 AM
David Carroll
David Carroll - avatar
+ 3
That, I do not know, I am not proficient enough in C# :/
7th Feb 2018, 7:30 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
Maybe some optimizations
7th Feb 2018, 7:30 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar