What is the best way to attach extenstion methods to static classes rather than to instances of a cl
Posted
by John Gietzen
on Stack Overflow
See other posts from Stack Overflow
or by John Gietzen
Published on 2010-03-30T12:47:33Z
Indexed on
2010/03/30
12:53 UTC
Read the original article
Hit count: 395
If I have a method for calculating the greatest common divisor of two integers as:
public static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
What would be the best way to attach that to the System.Math class?
Here are the three ways I have come up with:
public static int GCD(this int a, int b)
{
return b == 0 ? a : b.GCD(a % b);
}
// Lame...
var gcd = a.GCD(b);
and:
public static class RationalMath
{
public static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
}
// Lame...
var gcd = RationalMath.GCD(a, b);
and:
public static int GCD(this Type math, int a, int b)
{
return b == 0 ? a : typeof(Math).GCD(b, a % b);
}
// Neat?
var gcd = typeof(Math).GCD(a, b);
The desired syntax is Math.GCD
since that is the standard for all mathematical functions.
Any suggestions? What should I do to get the desired syntax?
© Stack Overflow or respective owner