C# If statement calling a method not working? -
here code:
static void main() { list<string> smalllist = new list<string>(new string[]{ " ", " "}); list<list<string>> biglist = new list<list<string>>(new list<string>[]{ smalllist, getsmalllist()}); if (biglist[0][0] == " ") { } if (biglist[0] == smalllist) { } if (biglist[1] == smalllist) { } if (biglist[1] == getsmalllist()) { } } public static list<string> getsmalllist() { list<string> list = new list<string>(new string[]{ " ", " "}); return list; } the first , second 'if' statements work. these make sense. third , fourth 'if' statements not work. can me understand why not?
if (biglist[0][0] == " ") this true because value of biglist[0][0] " ", , strings compared value. since have same value, comparison true.
if (biglist[0] == smalllist) this true because biglist[0] points same object in memory smalllist does. 2 references same thing. since compared reference, references equal.
if (biglist[1] == smalllist) this false because biglist[1] does not point same object in memory smalllist does. objects created same way, different objects. (much in same way 2 identical cars still different cars.) compared reference, , references different instances in memory.
if (biglist[1] == getsmalllist()) this false same reason previous one. in case it's more clear because getsmalllist() , explicitly create new instance of object in memory. continue analogy, identical car just rolled off assembly line. looks same, it's different car.
objects default compared equality reference (unless override functionality in class definition, or provide custom comparison logic). 2 instances of object, no matter how intuitively similar may appear, 2 separate instances.
Comments
Post a Comment