Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing IComparable<T>

Tags:

c#

generics

I am getting the following error message when trying to tweak Listing 3.4 from Jon Skeet's book, C# in depth...

The type 'list_3_4.Dog' cannot be used as type parameter 'T' in the generic type or method 'list_3_4.Program.CompareToDefault(T)'. There is no implicit reference conversion 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 do I add a reference type like a "Dog" to work with Jon Skeets code listing??? I understand that Dog needs to implement IComparable but I don't know how!

like image 757
dannyrosalex Avatar asked Oct 05 '12 14:10

dannyrosalex


2 Answers

You define the methods by saying you need a type T that is an 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 should do a null check somewhere. Read about default on msdn.

like image 102
gideon Avatar answered Oct 06 '22 00:10

gideon


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 );
      }
 }
like image 22
Alex Avatar answered Oct 06 '22 00:10

Alex