Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write nested generic function

Tags:

c#

I am trying to write a generic Heap Sort algorithm. I get the following error. What could be the reason?

The type T cannot be used as type parameter T in the generic type or method Heap.MainClass.MaxHeapify<T>(T[], int, int). There is no boxing or type parameter conversion from T to System.IComparable<T> (CS0314) (HeapSort)

like image 682
Nemo Avatar asked Jan 30 '12 06:01

Nemo


People also ask

How do you write a generic function?

Function types can create generics in the same way as normal functions, by adding the type parameter list <T> before the function type parameter list. You can use generics in the same places you'd add any other type in a function type (parameter or return types). Which then gets used as its own type.

How do you write a generic function in Java?

For static generic methods, the type parameter section must appear before the method's return type. The complete syntax for invoking this method would be: Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util. <Integer, String>compare(p1, p2);

Can we have generic function inside non generic class?

Yes, you can define a generic method in a non-generic class in Java.

What is generic with example in C#?

Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.


2 Answers

You need to specify the same generic constraint that T must implement IComparable<T> on the HeapSort function as well:

private static void HeapSort<T>(T[] items) where T : IComparable<T>

You specified this constraint on the MaxHeapify method and in order to call it, T must satisfy this condition.

like image 56
Darin Dimitrov Avatar answered Oct 09 '22 04:10

Darin Dimitrov


The MaxHeapify<T>() method has a generic constraint of where T : IComparable but your HeapSort<T>() method doesn't have it, and so the compiler is not able to resolve the call to MaxHeapify from HeapSort method. You should add a generic constraint of where : IComparable to your HeapSort<T>() method also.

private static void HeapSort<T>(T[] items) where T : IComparable<T>
like image 34
VSS Avatar answered Oct 09 '22 06:10

VSS