Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusing of using == operator in c#

Tags:

c#

.net

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); }
}
like image 993
mark Avatar asked Aug 29 '17 09:08

mark


1 Answers

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.

like image 149
René Vogt Avatar answered Oct 10 '22 07:10

René Vogt