Generic Methods with Generic Parameters in c#


The challenge

Make a method to calculate the Min. Difference in a list of numbers.

  • The input can be an Array, List, HashSet, IEnumerable
  • The size unknown
  • The type of number is unknown as well (int, long, float, double,…)

So we are looking to create a truly generic methose

The Code

public static T MinDifference<T>(this IEnumerable<T> numbers) 

   int count = 1;
   var _n = numbers.Cast<dynamic>().ToList();
   return (T)_n.Skip(1).Min(n => n - _n[count++ - 1]);


  • The return type of the function is **T** (Generic)
  • Parameter is **IEnumerable<T>**  (Generic)
  • Cast the parameter numbers as a **dynamic List**, this will allow you to make the calculations.  when you keep simply T, you will get an error when you try to subtract the numbers.
  • Cast the result to T


List<int> _dividors = _n.GetAllDividors().ToList();
HashSet<double> _ht = new HashSet<double>();
    _ht .Add(1.1);
    _ht .Add(0.2);
    _ht .Add(0.4);
    _ht .Add(1);

    _ht .Add(0.1);

double _r1 = _t1.MinDifference();
decimal[] _dec = new decimal[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var _rdec = _dec.MinDifference();

Array _dividors2 = _dividors .GetAllDividors().ToArray();


Whatever type of list of numbers you use, the size of the list, you used 1 method.

Frederik Van Lierde

Frederik Van Lierde

Main developer of the CodeHelper .Net Packages