List.Contains returns false, although it seems like it should return true

Sub pageload() Handles Me.Load
    Dim bom As New List(Of Car)

    Dim car1 As New Car With {.Name = "Pea", .Year = 2}
    Dim car2 As New Car With {.Name = "Pea", .Year = 2}

    bom.Add(car1)

    MsgBox(bom.Contains(car2))
End Sub

WHY??? I mean, the object has exactly the same data, so why does it say that it is not contained?

+3
source share
3 answers

The method Containschecks equality by calling the method Equalson objects. If you do not override the method Equalsin the class Carand do not implement your own means of comparison, the instances Carwill be considered equal by means of a reference identifier (which is the exact same object), not based on the fact that their contents are equal.

, , . : .

+15

, car , . - . , . . . , , - , .

car2, car1 (Dim car2 As New Car = car1), . . .

, , ( . ). , , , 10 , , 10 . - , , 10 10 .

, , .

Equals , , . ( Equals.) , .

+1

Your two cars are completely independent of each other.

Containschecks if any list item indicates the same object as the parameter you provided. And aren't these two objects logical.

If you want to do this, you must override the - Equalsmethod of yourCar

0
source

Source: https://habr.com/ru/post/1733257/


All Articles