I have written a C# extension method which currently works with an int. The code is simple - it determines if a given int starts with another int (without using string conversions) and returns either true or false:
namespace StartsWithNumberX
{
public static class IntExtensions
{
/// <summary>
/// Determine if the current number starts with another 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;
for (var i = 0; i < placeDiff; i++)
{
numberCopy = numberCopy/10;
}
return numberCopy == startsWith;
}
/// <summary>
/// Find the "place" of the number.
/// less than 10 = 1
/// less than 100 = 2
/// less than 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 to make this code more generic so the same code will work with other numeric types say, long
, double
, decimal
too.
Is it possible to do this in C#, or will I need to duplicate this code for the different number types?