“stringDemo” versus new string(“stringDemo”.ToCharArray);

please look at the below code:

using System;
class MyClass
{
    static void Main()
    {
        object o = ".NET Framework";
        object o1 = new string(".NET Framework".ToCharArray());
        Console.WriteLine(o == o1);
        Console.WriteLine(o.Equals(o1));
    }
}

and the result is: False True

and now consider this one:

using System;
class MyClass
{
    static void Main()
    {
        object o = ".NET Framework";
        object o1 = ".NET Framework";
        Console.WriteLine(o == o1);
        Console.WriteLine(o.Equals(o1));
    }
}

and the result is: True True

“==” compares if the object references are same while “.Equals()” compares if the contents are same. and i want to know what is different between these codes?!

object o1 = new string(".NET Framework".ToCharArray());

and

object o1 = ".NET Framework"; 

both of them turn out an object but why results are different?

Answers


both of them turn out an object but why results are different?

In the second case, you're using the same string constant for both the o and o1 assignment. C# guarantees that any two equal string constant expressions within the same program will refer to the same string object. So the values of o and o1 are the same reference.

While I can't find the more general form (for constant string expressions), your case is actually covered by section 2.4.4 of the C# spec:

When two or more string literals that are equivalent according to the string equality operator appear in the same program, these string literals refere to the same string instance.

EDIT: A quick note on the behaviour of ==:

  • If both operands have a compile-time type of ==, the overload provided by string will be used, which performs a content comparison
  • Otherwise, the "default" implementation which just compares references for equality will be used, as you stated in your question.

In your case, the compile-time types of the operands are both object, so it is genuinely using reference equality.


Need Your Help

Cypher/Neo4J: How to find interconnected neighbors_of_neighbors

neo4j cypher

I am playing around with Neo4J, and I have nodes of persons and cities visited. Lets say that I have visited London, and I want to see I want to create a query returning all cities that has been v...

JQuery function not firing on enter keypress

javascript jquery function key keypress

I have the following jQuery/js controlling a trello style input field. So when you click on the span element, it switches to an input field. Then after you finish editing the element and take focus...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.