DEV Community

Frederik Van Lierde
Frederik Van Lierde

Posted on • Edited on

4 1

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay