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

后端 未结 6 633
情书的邮戳
情书的邮戳 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条回答
  •  孤独总比滥情好
    2020-11-27 17:30

    Another example of the Discard Operator _ in C# 7 is to pattern match a variable of type object in a switch statement, which was recently added in C# 7:

    Code:

    static void Main(string[] args)
    {
        object x = 6.4; 
        switch (x)
        {
            case string _:
                Console.WriteLine("it is string");
                break;
            case double _:
                Console.WriteLine("it is double");
                break;
            case int _:
                Console.WriteLine("it is int");
                break;
            default:
                Console.WriteLine("it is Unknown type");
                break;
        }
    
        // end of main method
    }
    

    This code will match the type and discard the variable passed to the case ... _.

提交回复
热议问题