官术网_书友最值得收藏!

How to do it...

  1. The following code example will illustrate how we used to have to use TryParse to check if a string value is a valid integer. You will notice that we had to declare the integer variable intVal, which was used as the out variable. The intVal variable would just sort of hang there in mid air, usually not initialized and waiting to be used in  TryParse.
        string sValue = "500";

int intVal;
if (int.TryParse(sValue, out intVal))
{
WriteLine($"{intVal} is a valid integer");
// Do something with intVal
}
  1. In C# 7.0 this has been simplified, as can be seen in the following code example. We can now declare the out variable at the point where it is passed as an out parameter, like so:
        if (int.TryParse(sValue, out int intVal))
{
WriteLine($"{intVal} is a valid integer");
// Do something with intVal
}
  1. This is a small change, but a very nice one. Run the console application and check the output displayed.
  1. As we are declaring the out variable as an argument to the out parameter, the compiler will be able to infer what the type should be. This means that we can also use the var keyword, like this:
        if (int.TryParse(sValue, out var intVal))
{
WriteLine($"{intVal} is a valid integer");
// Do something with intVal
}
主站蜘蛛池模板: 射洪县| 卢龙县| 兰州市| 竹山县| 灵山县| 常山县| 新晃| 蕲春县| 丰县| 金塔县| 镇远县| 瑞昌市| 阿勒泰市| 德钦县| 开封县| 道真| 开远市| 肇源县| 龙川县| 化隆| 涞源县| 娄底市| 平罗县| 隆化县| 乐清市| 云梦县| 武隆县| 汉中市| 赞皇县| 榆社县| 文成县| 荣昌县| 屏山县| 福泉市| 天全县| 遂宁市| 瑞昌市| 衡水市| 安顺市| 三亚市| 杭州市|