I'm trying to write an extension method that will add the function HasFactor
to the class int
in C#. This works wonderfully, like so:
static class ExtendInt
{
public static bool HasFactor(this int source, int factor)
{
return (source % factor == 0);
}
}
class Program
{
static void Main()
{
int i = 50;
int f = 2;
bool b = i.HasFactor(f);
Console.WriteLine("Is {0} a factor of {1}? {2}",f,i,b);
Console.ReadLine();
}
}
This works great because variable i
in the Main()
method above is declared as an int
. However, if i
is declared as an Int16
or an Int64
, the extension method does not show up unless it is explicitly cast as an int
or Int32
.
I now would like to apply the same HasFactor
method to Int16
and Int64
. However, I'd rather not write separate extension methods for each type of int
. I could write a single method for Int64
and then explicitly cast everything as an Int64
or long
in order for the extension method to appear.
Ideally, I'd prefer to have the same extension method apply to all three types without having to copy and paste a lot of code.
Is this even possible in C#? If not, is there a recommended best-practice for this type of situation?