0

I am trying to print the coordinates if my object is found in the 2D array. Am using .Equals but it seems to be ignoring it.

    private void PrintCarInfo(Car car, object[,] matrix)
    {
        int xCoordinate = 0;
        int yCoordinate = 0;

        int w = matrix.GetLength(0);
        int h = matrix.GetLength(1);

        for (int x = 0; x < w; ++x)
        {
            for (int y = 0; y < h; ++y)
            {
                if (matrix[x, y].Equals(car))
                {
                    xCoordinate = x;
                    yCoordinate = y;
                }
            }
        }
    }

This is the Car class:

public class Car
{
    public int Index { get; set; }

    public string Name { get; set; }

    public bool Manual { get; set; }

    public bool Diesel { get; set; }

    public Car()
    {

    }

    public Car(Car car)
    {
        Index = car.Index;
        Name = car.Name;
        Manual = car.Manual;
        Diesel = car.Diesel;
    }
}

This is what I get when debug from the 2D array:

[1,1] {Toyota (15)}
marrs
  • 11
  • 3
  • If you don't override `Equals` then an object won't be equal unless it is the actual same instance, even if all the properties are equal. – Jodrell Jan 21 '19 at 14:05
  • As an aside, I'd prefer a [jagged array to a multi-dimensional array](https://stackoverflow.com/questions/4648914/why-we-have-both-jagged-array-and-multidimensional-array). – Jodrell Jan 21 '19 at 14:08
  • @Jodrell - jagged (array-of-array) is a little faster but unless there is a direct need for a non-rectangular shape I would prefer multi dim. Keep it simple. – bommelding Jan 21 '19 at 14:12

1 Answers1

2

Am using .Equals but it seems to be ignoring it.

Yes,

 if (matrix[x, y].Equals(car))

will only work

  1. When car is a reference to an instance in the matrix, or
  2. When you override Car.Equals

The default comparison for classes is Reference Equality. That will only work when the search element car is the exact same object as is in the matrix.

When you want to compare to a different object but with the same property values, you will have to implement Equality by yourself.

bommelding
  • 2,969
  • 9
  • 14