maybe you should use a library.
For that particular function? For
modinv only?
Looks like for all. One more mistake is using
^2 for square. In C# (and C, C++, etc.) this is XOR with 2.
Do you really know C#? When translating code you should first understand what it does, both original and translated. Anyway, this must be a good learning experience for you. Maybe check what it does step by step and consult manuals more.