IComparable <T> implementation
I get the following error message when I try to customize Listing 3.4 from a Jon Skeet book, C # in depth ...
The type "list_3_4.Dog" cannot be used as a parameter of type "T" in the generic type or method "list_3_4.Program.CompareToDefault (T)". There is no implicit conversion of links from "list_3_4.Dog" to "System.IComparable".
Here is my code ...
using System; namespace list_3_4 { class Program { static void Main(string[] args) { //string mystring; Dog d = new Dog("howie"); Console.WriteLine(CompareToDefault("x")); Console.WriteLine(CompareToDefault(10)); Console.WriteLine(CompareToDefault(0)); Console.WriteLine(CompareToDefault(-10)); Console.WriteLine(CompareToDefault(DateTime.MinValue)); Console.WriteLine(CompareToDefault(d)); Console.ReadKey(); } static int CompareToDefault<T> (T value) where T: IComparable<T> { return value.CompareTo(default(T)); } } public class Dog { private string _name; public Dog(string name) { _name = name; } } } How to add a reference type, for example, "Dog" to work with a list of Jon Skeets codes ??? I understand that the dog needs to implement IComparable, but I donβt know how to do it.
You define methods by indicating that you need a type T , which is IComparable<T> :
where T: IComparable<T> But Dog does not implement IComparable<Dog>
You need to do:
public class Dog : IComparable<Dog> { //this will allow you to do a quick name comparison public string Name { get; set;} public int CompareTo(Dog other) {//compare dogs by name return this._name.CompareTo(other.Name); } } Note : default(T) will return null for reference types, so you need to do a null check. Learn more about default msdn .
Your Dog class should implement IComparable<T> .
public class Dog: IComparable<Dog> { private string _name; public Dog(string name) { _name = name; } public int CompareTo( Dog other ) { if (other == null) return 1; return string.Compare( _name, other._name ); } }