C#7: Underscore ( _ ) & Star ( * ) in Out variable

后端 未结 6 624
情书的邮戳
情书的邮戳 2020-11-27 17:08

I was reading about new out variable features in C#7 here. I have two questions:

  1. It says

    We allow \"discards\" as out parameters as w

6条回答
  •  萌比男神i
    2020-11-27 17:32

    Q: ... we can do so in pre C#7.0 too:

    var _;
    if (Int.TryParse(str, out _))
    

    or am I missing something here?

    That isn't the same thing.
    Your code is making an assignment.

    In C# 7.0 _ is not a variable, it tells the compiler to discard the value
    (unless you have declared _ as a variable... if you do that the variable is used instead of the discard symbol)

    Example: you can use _ as a sting and an int in the same line of code:

    string a; 
    int b;
    Test(out a, out b);
    Test(out _, out _);
    
    //...
    
    void Test(out string a, out int b)
    {
       //...
    }
    

提交回复
热议问题