-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Description
It seems like the TSelf TSelf.Create<TOther>(TOther value) (and friends) are what we can call ConvertFrom (in TypeConverter lingo). And there are no equivalent of TOther TSelf.ConvertTo(TSelf value).
So if I code up new number type
public readonly partial struct Fraction : IComparable<Fraction>, IEquatable<Fraction>, ISpanFormattable, IComparable
if FEATURE_GENERIC_MATH
#pragma warning disable SA1001, CA2252 // SA1001: Comma positioning; CA2252: Preview Features
, IMinMaxValue<Fraction>
, ISignedNumber<Fraction>
#pragma warning restore SA1001, CA2252
#endif // FEATURE_GENERIC_MATH
{
// impl not important
}I will implement the Create static method (and friends) (supporting whatever other numeric type I choose). But if I need to use this Fraction type somewhere else generically (in places where other number types can take its place, aka polymorphic programming), and need something like the following old hacky generic operators helper/util class
public static class Arithmetic
{
// I cannot modify 'int Int32.Create(TOther value)', and
// therefore I cannot convert a Fraction to an Int32 value
// We need both 'TSelf TSelf.ConvertFrom(TOther value)' and TOther 'TSelf.ConvertTo(TSelf value)'
public static int ToInt32<T>(T value) where T : struct
{
if (typeof(T) == typeof(decimal))
{
return (int)(object)((int)decimal.Floor((decimal)(object)value));
}
if (typeof(T) == typeof(Fraction))
{
return (int)(object)(Fraction.Floor((Fraction)(object)value).ToInt32());
}
throw new NotSupportedException("Type is not supported");
}
// This can be done via 'Fraction Fraction.Create(TOther value)'
public static T FromInt32<T>(int value) where T : struct
{
if (typeof(T) == typeof(decimal))
{
return (T)(object)(new decimal(value));
}
if (typeof(T) == typeof(Fraction))
{
return (T)(object)(new Fraction(value));
}
throw new NotSupportedException("Type is not supported");
}
}And want to translate this Arithmetic helper into the new generic math preview feature in .NET 6
public static class Arithmetic
{
// I made up the ConvertTo static polymorphic method (that does not exist on INumber<TSelf>)
public static int ToInt32<T>(T value) where T : INumber<T> => T.ConvertTo<int>(value);
public static T FromInt32<T>(int value) where T : INumber<T> => T.Create(value);
}but of course this does NOT compile.
How can I solve this using the new generic math interfaces, when I cannot change the Int32.Create (ConvertFrom) code in the BCL?
We need something like TOther TSelf.INumber<T>.ConvertTo(TSelf value), that I can support on my own (non BCL) number type.
I think the conversion part of INumber have to be revisited.