Why (object) s1! =(object) s2? | SoloLearn: Learn to code for FREE!

+2

Why (object) s1! =(object) s2?

https://code.sololearn.com/cL6l85GqfIhH/?ref=app

c#

2/7/2018 6:04:00 AM

Garry Evmenchik

10 Answers

New Answer

+10

C# isn't my strong suit either. Most of my work is in C, Embedded C, System C, C++, and a bevy of scripting languages. Perhaps @David Carroll could enlighten us all 🙂

+9

Because s1 and s2 have different object IDs, (object) s1 will never be equal to (object) s2 when comparing that way. The only way for s1 to equal s2 is by manually saying that s2 = s1.

+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

+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/

+7

@David, Thanks David for explaining the internals and the link, being a C++ person i had forgotton about IL :)

+4

@Baptiste and @Ace Why s2 and s3 have the same reference while s1 and s2 does not. All three have same contents though.

+3

That, I do not know, I am not proficient enough in C# :/

+2

Maybe some optimizations

+2

Oh ok Baptiste, I too do not know yet :(