Generic extension method in C# -
i have written c# extension method works int. code simple - determines if given int starts int (without using string conversions) , returns either true or false:
namespace startswithnumberx { public static class intextensions { /// <summary> /// determine if current number starts number. /// </summary> /// <param name="number"></param> /// <param name="startswith"></param> /// <returns></returns> public static bool startswith(this int number, int startswith) { var inputplace = number.findplacenumber(); var compareplace = startswith.findplacenumber(); var placediff = inputplace - compareplace; var numbercopy = number; (var = 0; < placediff; i++) { numbercopy = numbercopy/10; } return numbercopy == startswith; } /// <summary> /// find "place" of number. /// less 10 = 1 /// less 100 = 2 /// less 1000 = 3 /// etc. /// </summary> /// <param name="number"></param> /// <returns></returns> private static int findplacenumber(this int number) { var placenumber = 0; while (number > 0) { number = number/10; if (number > 0) { placenumber++; } else { placenumber++; break; } } return placenumber; } } }
i want make code more generic same code work other numeric types say, long
, double
, decimal
too.
is possible in c#, or need duplicate code different number types?
i have not found solution make extension method more generic have idea how make code easier. make normal findplacenumber-method accept dynamic parameter
private static int _findplacenumber(dynamic number) { var placenumber = 0; while (number > 0) { number = number / 10; if (number > 0) { placenumber++; } else { placenumber++; break; } } return placenumber; }
then can make 3 short extension methods, call mehthod this.
public static int findplacenumber(this int number) { return _findplacenumber(number); } public static int findplacenumber(this double number) { return _findplacenumber(number); } public static int findplacenumber(this decimal number) { return _findplacenumber(number); }
this fast option make extension method more "generic" without writing code. disadvantage of dynamic binding is, slower static typing.
Comments
Post a Comment