I’m trying to follow some example in learning sorting arrays. Example use Id as integer to sort by this property, since my object use Guid datatype instead of int I’m decided to use Created DateTime property to sort array. Here’s the code
Car.cs
public class Car:ICar,IComparable
{
... properties
int IComparable.CompareTo(object)
{
Car temp = obj as Car;
if (temp != null)
{
if (this.Created > temp.Created)
return 1;
if (this.Created < temp.Created)
return -1;
else
return 0;
}
else {throw new ArgumentException("Parameter is not a Car object");}
}
}
Garage.cs
public class Garage : IEnumerable
{
private Car[] cars = new Car[4];
public Garage()
{
cars[0] = new Car() { Id = Guid.NewGuid(), Name = "Corolla", Created = DateTime.UtcNow.AddHours(3), CurrentSpeed = 90 };
cars[1] = new Car() { Id = Guid.NewGuid(), Name = "Mazda", Created = DateTime.UtcNow.AddHours(2), CurrentSpeed = 80 };
}
...
}
Program.cs
static void Main(string[] args)
{
Garage cars = new Garage();
Console.WriteLine("sorting array:");
Array.Sort(cars); // error occured
}
Error 2 Argument 1: cannot convert from ‘Car’ to ‘System.Array’
This solution assumes you want to sort the array in place, and not create a new one.
To your
Garageclass, add a method (so you don’t have to expose the inner array):Then call this method from your program:
I’ve taken the liberty of calling your
Garageobjectgaragerather thancarswhich can be confusing.I haven’t tested this, but it’s so straightforward, that it should work.