So, I was doing a lesson in a book, and as I sometimes do I started playing around with it and trying a few things not specifically spelled out. And, turns out I hit something I don't quite understand. The section was on IComparable<T>. I've worked with interfaces before, so I figured this would work:
Buy, my console output was:
...Whaaaaa? Why isn't if (ducks is IComparable<Duck>) returning true?
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Duck> ducks = new List<Duck>()
{
new Duck() { Kind = KindOfDuck.Mallard, Size = 17},
new Duck() { Kind = KindOfDuck.Muscovy, Size = 18},
new Duck() { Kind = KindOfDuck.Decoy, Size = 14 },
new Duck() { Kind = KindOfDuck.Muscovy, Size = 11 },
new Duck() { Kind = KindOfDuck.Mallard, Size = 14 },
new Duck() { Kind = KindOfDuck.Decoy, Size = 13 },
};
if (ducks is IComparable<Duck>)
ducks.Sort();
else
Console.WriteLine("I can't sort the ducks!");
printDucks(ducks);
Console.ReadKey();
}
private static void printDucks(List<Duck> ducks)
{
foreach (Duck duck in ducks)
Console.WriteLine(duck.Size.ToString() + "-inch " + duck.Kind.ToString());
Console.WriteLine("End of ducks!");
}
}
}
using System;
namespace ConsoleApplication1
{
class Duck : IComparable<Duck>
{
public int Size;
public KindOfDuck Kind;
public int CompareTo(Duck other)
{
if (this.Size > other.Size)
return 1;
else if (this.Size == other.Size)
return 0;
else
return -1;
}
}
enum KindOfDuck
{
Mallard,
Muscovy,
Decoy,
}
}
Buy, my console output was:
I can't sort the ducks! 17-inch Mallard 18-inch Muscovy 14-inch Decoy 11-inch Muscovy 14-inch Mallard 13-inch Decoy End of ducks!
...Whaaaaa? Why isn't if (ducks is IComparable<Duck>) returning true?