Avatar ·

How to check if a string is a number in C#? (IsNumeric analog)

Hello colleagues! I'm a beginner C# developer and I've encountered a typical task: I need to check that a user-entered string contains exactly a number, not some garbage. For example, a user enters their age in a text field, and before saving it as an int, I want to make sure it's not "twenty" or "abc123".\n\nI tried using Convert.ToInt32() inside a try-catch, but it looks cumbersome and, as I think, not very performant. Moreover, I need to distinguish integers from floating-point numbers. Is there a built-in analog of the IsNumeric function from VB.NET in C# or some elegant way to do this?\n\nHere's how I'm currently trying to solve the problem:\n\n
string userInput = "123.45";\ntry\n{\n    int number = Convert.ToInt32(userInput);\n    Console.WriteLi