SuperMinefudge
SuperMinefudge

Reputation: 301

Comparing Generic Values

So i wanted to make a generic method that makes you an array with a specific length that you insert into and it sorts it at the same time. so i was transfering it from int to generic T and i stumbled into a problem while trying to compare 2 variables of T. this is the code so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
class Program
{
    public static T[] insertWhileSorting<T>(int x)
    {
        T[] arr = new T[x];
        for (int i = 0, k; i < arr.Length; i++)
        {
            T value = (T)Convert.ChangeType(Console.ReadLine(), typeof(T));

            for (k = i; k > 0 && value.CompareTo(arr[k - 1]) < 0; --k) arr[k] = arr[k - 1];

            arr[k] = value;
        }
        return arr;
    }
    static void Main(string[] args)
    {
        int[] arr = insertWhileSorting<int>(5);
        Console.WriteLine(string.Join(", ", arr));
    }
  }
}

and yes i know(i think)that simply inserting the values into an array and then sorting it is better but i'm doing it for an assignment

Upvotes: 1

Views: 440

Answers (1)

Mong Zhu
Mong Zhu

Reputation: 23732

You would need to assert that the type T as implemented IComparable<T>. Using the where key word you can restrict the type T with a condition that T has to implement IComparable<T>:

 public static T[] insertWhileSorting<T>(int x) where T: IComparable<T>

IComparable demands that the class in question implements the method CompareTo. Now the compiler should stop complaining that

"T" does not contain a definition for "CompareTo" and cannot find an extension method "CompareTo"

EDIT:

this line can get you easily into trouble:

T value = (T)Convert.ChangeType(Console.ReadLine(), typeof(T));

because the user can type simply a string like "break" which would result in an FormatException if you initially called it like this:

int [] adda = insertWhileSorting<int>(5);

You can put this whole conversion and sorting routine into a try catch clause and give a warning when it crashes:

for (int i = 0, k; i < arr.Length; i++)
{
    try
    {
        T value = (T)Convert.ChangeType(Console.ReadLine(), typeof(T));

        for (k = i; k > 0 && value.CompareTo(arr[k - 1]) < 0; --k) arr[k] = arr[k - 1];

        arr[k] = value;
    }
    catch (Exception ex)
    {
        Console.WriteLine("That stuff was not convertible!");
        Console.WriteLine("Error: " + ex.Message);
    }

}

Upvotes: 3

Related Questions