Suppose we have the following code:
int item1=5;
int item2=6;
int item3=7;
int item4=5;
List<int> items= new List<int> {item1,item2,item3};
bool result= items.Contains(item4);
Now, the variable result should be:
a)false, because there is not a variable "item4" in the list.
b)true, because the value of item4 which is 5, is among the values of the items in the list.
What is the correct answer and why? Could you please explain how the method Contains uses the Equals method?
CodePudding user response:
b. It doesn't matter if you write item1
, item4
, 5
or 10/2
; they all evaluate to the number five.
CodePudding user response:
Short answer: B.
Long answer:
What List.Contains does is that it checks whether or not a list contains a value, e.g an int, bool or any other object. If you are wondering about the Equals method, well, the Equals method checks if two objects are the same value-wise.
This means that the code for Contains is most likely just
public void bool Contains(T value){
for(int i = 0; i < Count; i ){
if(self[i].Equals(value)) // Could prob be something else, and might use "==" instead of equals
return true;
}
return false;
}
CodePudding user response:
Read about reference types vs value types! List is a reference type! wich is stored on the heap! and get pointer for the value in the stack! so your statment! does compare the value itself! not the pointer!
bool result= items.Contains(item4); //True
Resource for value types vs reference types: https://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type