D
D
Dobriy_Chelovek33432020-02-24 22:04:01
.NET
Dobriy_Chelovek3343, 2020-02-24 22:04:01

How to make a "universal" sort?

In general, I'm dealing with quicksort here, and when I started writing, I ran into the problem of static typing. Algorithm for int double long etc. is no different, but due to type differences, you need to produce overloads and therefore there is a huge duplication of code. Is there any way to avoid this?
PS
dynamic is not suitable because the performance goes into oblivion.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
2
2CHEVSKII, 2020-02-24
@Dobriy_Chelovek3343

If I understand you correctly, then you can use the generic type constraint to IComparable, it is implemented by all primitives.

public IEnumerable<T> Sort<T>(IEnumerable<T> collection) where T : IComparable
    {
      foreach(var item in collection)
      {
        var result = item.CompareTo(new object()/* <- объект для сравнения */);
        // и так далее
      }
    }

P
Pavel Shvedov, 2020-02-24
@mmmaaak

Generic Templates (Programmer's Guide...

D
Denis Zagaevsky, 2020-02-24
@zagayevskiy

Generics

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question