int.TryParse syntatic sugar

后端 未结 10 1412
广开言路
广开言路 2020-12-14 14:15

int.TryPrase is great and all, but there is only one problem...it takes at least two lines of code to use:

int intValue;
string stringValue = \"         


        
10条回答
  •  一个人的身影
    2020-12-14 14:36

    This answer is only for those who use at least C# 7.

    You can now declare the out parameter inline.

    int.TryParse("123", out var result);
    

    Exemplary usage:

    if (int.TryParse("123", out var result)) {
        //do something with the successfully parsed integer
        Console.WriteLine(result);
    } else {
        Console.WriteLine("That wasn't an integer!");
    }
    

    MSDN: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables

提交回复
热议问题