Since both are reference types, why do they have different results?
Because string
objects are highly optimized. In particular, since they're immutable, they can be interned by the compiler to prevent duplication.
If you have two different string
objects that both represent the exact same string of characters (as in your example), the compiler will recognize that and maintain only one instance of the actual string object.
The result is that both the s1
and s2
objects actually are the same object as far as the compiler is concerned and even reference the same location in memory.
This bookkeeping happens behind the scenes in something called an "intern table", but that's not really something you need to worry yourself with. The important thing is that all string literals are interned by default by the compiler.
The same kind of thing does not happen for StringBuilder
objects, because they are not immutable. They're designed to allow you to modify a string object, and as such, the optimizations don't make much sense. That's why your sb1
and sb2
objects are actually seen as two different objects.
The rule of thumb is quite simple: Use string
by default, or when you want a single immutable string of characters. Only use StringBuilder
when you want to modify the same string multiple times, say in a loop or other relatively short section of code.
Relevant reading: Optimizing C# String Performance
StringBuilder
object references. They're two separate objects.StringBuilder
. It is really about "why do two string variables initialized with two string literals containing the same character sequence compare as being the same object"?string s2 = "hel" + "lo";
to see that it doesn't have anything to do with types.