DEV Community

Frederik Van Lierde
Frederik Van Lierde

Posted on • Updated on

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 method

The Code

public static T MinDifference<T>(this IEnumerable<T> numbers) 
{
   int count = 1;
   var _n = numbers.Cast<dynamic>().ToList();
   _n.Sort();
   return (T)_n.Skip(1).Min(n => n - _n[count++ - 1]);
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  • 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

Result

List<int> _dividors = _n.GetAllDividors().ToList();
_dividors.MinDifference();

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();
_dividors2.MinDifference();
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)