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

New changes with the out variables

Currently in C#, we need to first declare a variable before we pass it as an out parameter to a method. You can use a var while declaration if you initialize them in the same line, but when you don't want to initialize explicitly, you must declare them, specifying the full type:

    // predeclaration of 'out' variable was mandatory 
    int result; // or, var result = 0; 
    string value = "125"; 
 
    int.TryParse(value, out result); 
 
    Console.WriteLine("The result is: " + result); 

In C# 7.0, the out variables can be declared right at the point where they are passed as an out parameter to a method. You can now directly write int.TryParse(value, out int result); and get the value of the out parameter, to use it in the scope of the enclosing block:

    static void Main(string[] args) 
    { 
      string value = "125"; 
      int.TryParse(value, out int result); 
      Console.WriteLine("Result:  " + result); 
    } 

You can also use var instead of a strong type declaration, like int.TryParse(value, out var result);, and the compiler will define it properly:

    static void Main(string[] args) 
    { 
      string value = "125"; 
      int.TryParse(value, out var result); 
      Console.WriteLine("Result:  " + result); 
    } 
To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

If you have already written code in the existing way of declaration before passing the out parameter to a method, Visual Studio 2017 will allow you to leverage this new feature of C# 7.0 from the light bulb icon:

From the popup, you can fix all the similar occurrences, in the current document, the entire project, or at the solution level, by clicking the links highlighted as shown in the preceding screenshot.

主站蜘蛛池模板: 凤城市| 大英县| 德清县| 阿尔山市| 武冈市| 双桥区| 大庆市| 简阳市| 龙泉市| 德兴市| 蒲江县| 普兰县| 循化| 金门县| 红安县| 县级市| 泽库县| 西吉县| 津南区| 凤庆县| 临高县| 青阳县| 沽源县| 体育| 大方县| 汉川市| 武义县| 阿克苏市| 凤翔县| 平原县| 达日县| 南皮县| 芦山县| 开原市| 渝中区| 遵化市| 县级市| 洛隆县| 彰武县| 龙口市| 永川市|