I have the following implementation
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// item.Equals().
//
public bool Contains(T item) {
if ((Object) item == null) {
for(int i=0; i<_size; i++)
if ((Object) _items[i] == null)
return true;
return false;
}
else {
EqualityComparer<T> c = EqualityComparer<T>.Default;
for(int i=0; i<_size; i++) {
if (c.Equals(_items[i], item)) return true;
}
return false;
}
}
If item
is a struct
value type, does the flow go into the if
block, rather than the else
block? I am confused about this implementation.
Can anyone explain to me how the Contains
method can evaluate value types like a struct
?
The if
part is only checking if we are looking for null
item in the list. If we do, then it goes through the list and looks for null
value in the items of the list. This part is only valid for reference types, because value types cannot be null
.
The else
part of the other hand is doing all the checking in cases when item is not null
, so this code is used for structs
as well. What it does is it gets a default equality comparer for the type ( EqualityComparer<T> c = EqualityComparer<T>.Default
) and uses this comparer to find the item in the list.
What you need to understand is the difference between a value type
and a reference type
.
struct
, just like an int
, long
, etc. is not stored on the heap
but on the stack
. A reference type
has a pointer (which is a memory address) stored on the stack
that points to the actual object data is stored on the heap
.
(Go read up on the difference between a stack and a heap.)
However, adding a struct
to something like a ArrayList
or even List<object>
will still work because it will most probably be boxed into a reference type
first and thus a struct
wil not be null
, even if you passed a default(<struct type>)
it will still not be null
.
Then it will follow like @dotnetom has explained with the else
part executing and evaluating wether a struct
is in the collection or not.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.