Why am I getting these out parameter errors in C#?

前端 未结 5 1466
孤独总比滥情好
孤独总比滥情好 2020-12-19 02:04

I am new to C#. I\'ve tried this with out parameter in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Firs         


        
5条回答
  •  轮回少年
    2020-12-19 02:09

    As of C# 7.0 the ability to declare a variable right at the point where it is passed as an out argument was introduced.

    Before:

    public void PrintCoordinates(Point p)
    {
        int x, y; // have to "predeclare"
        p.GetCoordinates(out x, out y);
        WriteLine($"({x}, {y})");
    }
    

    C# 7.0

    public void PrintCoordinates(Point p)
    {
        p.GetCoordinates(out int x, out int y);
        WriteLine($"({x}, {y})");
    }
    

    You can even use var key word:

    p.GetCoordinates(out var x, out var y);
    

    Be carefull with the scope of out parameter. For example, in the following code, "i" is only used within if-statement:

    public void PrintStars(string s)
    {
        if (int.TryParse(s, out var i)) { WriteLine(new string('*', i)); }
        else { WriteLine("Cloudy - no stars tonight!"); }
    }
    

    Further information can be found here. This link is not only about out parameter, but all the new features introduced in c# 7.0

提交回复
热议问题