C
C#2y ago
DaVinki

✅ Creating a number generically?

Is it possible to do this? For example, here's this basic method that gets the digits of any object implementing INumber:
public static IEnumerable<TNumber> GetDigits<TNumber>(TNumber number, TNumber ten) where TNumber : INumber<TNumber>
{
List<TNumber> digits = new();
while (number > TNumber.Zero)
{
digits.Add(number % ten);
number /= ten;
}

digits.Reverse();
return digits;
}
public static IEnumerable<TNumber> GetDigits<TNumber>(TNumber number, TNumber ten) where TNumber : INumber<TNumber>
{
List<TNumber> digits = new();
while (number > TNumber.Zero)
{
digits.Add(number % ten);
number /= ten;
}

digits.Reverse();
return digits;
}
Instead of having to pass 10 into the method, would there be a way to create the 10 inside of the method to hide it from the user?
2 Replies
vdvman1
vdvman12y ago
INumber<T> implements INumberBase<T> which has a couple Create... methods So TNumber.CreateChecked(10), TNumber.CreateSaturating(10), or TNumber.CreateTruncating(10) should work
DaVinki
DaVinkiOP2y ago
Ah that works, thank you
Want results from more Discord servers?
Add your server