I recently learned about Stack and Heap and I wanted to ask a question concerning it. I've been "experimenting" with strings and I cannot explain - why is the following true if I am creating two different blocks of memory on the heap?
static void Main()
{
string test = "yes";
string secondTest = "yes";
Console.WriteLine(test == secondTest); //true
string thirdTest = new string("yes");
Console.WriteLine(secondTest == thirdTest); //true
}
The first string named test
is the same as secondTest
, because they have the same reference value, but when I create the third string thirdTest
am I not creating a new block of memory on the heap by using "new"?
Why is it still true?
My guess:
What I wrote is exactly the same and I misunderstood the new
operator, since when I watched tutorials, they were in Java language.
String name = "John"
String aThirdName = new String("John")
System.out.printIn(name == aThirdName); // false
This means that what I thought was different
(string test = "yes") = (string thirdTest = new string("yes"))
is actually the same. (By that I mean that those two lines are analogical)
If my guess is right, how do I create a new memory block on the heap with the same value? (I want to know, just for learning purposes, I know that it is ineffective for the memory to have a lot of variables that have the same value that are on different memory blocks inside the heap)
CodePudding user response:
As mentioned in comments, string
is a bad example since it has the ==
operator overridden and the equals
method overridden. For string, it is a reference type, but due to many overrides and other behavior it effectively behaves (in most cases) like a value type (especially in regards to equality).
That being said, if you were to create a simple class you'll find your test behaves exactly as you'd expect.
Snippets of the overridden equality in String to give you some context.
public static bool operator ==(string? a, string? b)
{
return string.Equals(a, b);
}
// Determines whether two Strings match.
public static bool Equals(string? a, string? b)
{
if (object.ReferenceEquals(a,b))
{
return true;
}
if (a is null || b is null || a.Length != b.Length)
{
return false;
}
return EqualsHelper(a, b);
}
It then starts down a rabbit hole of code with EqualsHelper
that's not worth chasing in here (if you're interested, you can decompile it or find it online).
CodePudding user response:
string firstTest=new string("test")
and string secondTest="test"
are the same, second version is just syntactic sugar. About why firstTest==secondTest //true
, that's why class String override method Equals
and operator (==) is also overriden and use Equals
.