[Solved] C# If statement calling a method not working?


if (bigList[0][0] == " ")

This is true because the value of bigList[0][0] is also " ", and the strings are compared by their value. Since they have the same value, the comparison is true.

if (bigList[0] == smallList)

This is true because bigList[0] points to the same object in memory as smallList does. They are two references to the same thing. Since they are compared by reference, the references are equal.

if (bigList[1] == smallList)

This is false because bigList[1] does not point to the same object in memory as smallList does. The objects were created the same way, but they are different objects. (Much in the same way that two identical cars are still different cars.) They are compared by reference, and the references are to different instances in memory.

if (bigList[1] == getSmallList())

This is false for the same reason as the previous one. Only in this case it’s more clear because getSmallList() is immediately and explicitly create a new instance of an object in memory. To continue the analogy, another identical car just rolled off the assembly line. It looks the same, but it’s a different car.

Objects are by default compared for equality by reference (unless you override that functionality in the class definition, or provide custom comparison logic). Any two instances of an object, no matter how intuitively similar they may appear, are two separate instances.

1

solved C# If statement calling a method not working?