Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Factorial function in C#

Tags:

c#

generics

I want to write a generic function to calculate factorial in C# ... like:

 static T Factorial<T>(T n)
        {
            if (n <= 1)
                return 1;

            return Factorial<T>(n - 1);
        }

but obviously having restriction that we can't perform operations on type 'T'. any alternative?

like image 257
mqpasta Avatar asked Dec 10 '22 17:12

mqpasta


1 Answers

The problem is that generics don't support operators because they are static methods, and not part of an interface. However, you could probably use Generic Operators, which is available in the Miscellaneous Utility Library.

like image 152
Nick Avatar answered Dec 22 '22 09:12

Nick