Showing posts with label Generic math C# 11. Show all posts
Showing posts with label Generic math C# 11. Show all posts

Saturday, 4 March 2023

Generic math - Factorial method

Here is a example of a generic math factorial method in C# 11. Generic math allows you to make numeric methods that makes use of the INumber generic interface, which got many static virtual methods where you can make a numeric method that supports different kinds of number types, such as decimal, int, float and double. The code below calculates the factorial of some values in an array. We have inserted a double value here that shows that Factorial of a double or any number with decimal works a bit different than ints, as the decimal part takes part here. The factorial of 0! is defined as 1 and we multiply n with n-1 as long as n > 0. Note the use of T.One and T.Zero here, defined as
static virtual members of the different number types in C#.


void Main()
{
	var someNums = new[] { 1, 2, 3, 3.141592, 5};
	var fact = someNums.Select(n =>  Factorial(n));
	fact.Dump();
	
}

T Factorial<T>(T num)
where T : INumber<T>
{
	var result = T.One;
	while (num > T.Zero){
		result *= num;
		num--;
	}
	return result;
}


Output shows the result in Linqpad 7 after having specified using .NET 7: