Context:
I am implementing a BigRational struct in C# which requires various arithmetic and comparison overloads. The code in many of the overloads look exactly the same because of the use of var
. On top of this I am getting a warning for CA2225 which states that various operators need a "friendly alternatively named" method. See https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2225
Since many arithmetic operators are overloaded for
- (BigRational, BigRational) -> BigRational
- (BigRational, BigInteger) -> BigRational
- (BigInteger, BigRational) -> BigRational
- (BigRational, long) -> BigRational
- (long, BigRational) -> BigRational
- (BigRational, ulong) -> BigRational
- (ulong, BigRational) -> BigRational
and comparison operators for
- (BigRational, BigRational) -> bool
- (BigRational, BigInteger) -> bool
- (BigInteger, BigRational) -> bool
- (BigRational, long) -> bool
- (long, BigRational) -> bool
- (BigRational, ulong) -> bool
- (ulong, BigRational) -> bool
this results in a significant amount of duplicate code and boilerplate.
Question:
Is there a simple way to use C# 9 style generators to implement this?
Side Thought:
It would be great if C# could get overload generation built into the language so that
public static BigRational Add<T>(BigRational augend, T addend)
where T overloads: BigInteger, long, ulong
{
// use var in code...
}
is equivalent to
public static BigRational Add(BigRational augend, BigInteger addend)
{
}
public static BigRational Add(BigRational augend, long addend)
{
}
public static BigRational Add(BigRational augend, ulong addend)
{
}
This would also allow one to write a single function for types that do not share a base class or interface, but have very similar APIs.