Home > Enterprise >  Contains method in C#
Contains method in C#

Time:08-22

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:

  • Related