C# testing to see if a string is an integer?

后端 未结 10 1412
北恋
北恋 2020-11-28 12:00

I\'m just curious as to whether there is something built into either the C# language or the .NET Framework that tests to see if something is an integer

if (x         


        
10条回答
  •  旧巷少年郎
    2020-11-28 12:27

    If you only want to check whether it's a string or not, you can place the "out int" keywords directly inside a method call. According to dotnetperls.com website, older versions of C# do not allow this syntax. By doing this, you can reduce the line count of the program.

    string x = "text or int";
    if (int.TryParse(x, out int output))
    {
      // Console.WriteLine(x);
      // x is an int
      // Do something
    }
    else
    {
      // x is not an int
    }
    

    If you also want to get the int values, you can write like this.

    Method 1

    string x = "text or int";
    int value = 0;
    if(int.TryParse(x, out value))
    {
      // x is an int
      // Do something
    }
      else
    {
      // x is not an int
    }
    

    Method 2

    string x = "text or int";
    int num = Convert.ToInt32(x);
    Console.WriteLine(num);
    

    Referece: https://www.dotnetperls.com/parse

提交回复
热议问题