I am confusing about using == in (c#)
when I use literal string like here:
object a="hello";
object b="hello";
the comparison a==b will be true.
but when I use object like here:
object c=new StringBuilder("hello").ToString();
object d=new StringBuilder("hello").ToString();
the comparison a==b will be false.
even though a,b,c,d all of type System.Object in compile time and
== operator compare values depends on their values in compile time.
I use extension method to get type of varabiles during compile time:
public static class MiscExtensions
{
public static Type GetCompileTimeType<T>(this T dummy)
{ return typeof(T); }
}
object a="hello";
object b="hello";
Here the compiler creates a single string instance for the literal "hello". So a and b point to the same instance.
In your second snippet c and d point to different string instances.
The important point however is that a == b and c == d don't call the == operator of the string class, but of object. So a simple reference comparison is executed, not a string comparison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With