CSharp - Method Parameter out variables discards

Introduction

You can declare out variables when calling methods.

You can discard the out variables that you're uninterested in with an underscore:

Split("this is a test", out string a, out _);   // Discard the 2nd param
Console.WriteLine (a);

The compiler treats the underscore as a special symbol, called a discard.

Demo

using System;
class Test/*from  www  .j av  a2s .  c  o  m*/
{
   static void Split (string name, out string firstNames,out string lastName)
   {
          int i = name.LastIndexOf (' ');
          firstNames = name.Substring (0, i);
          lastName   = name.Substring (i + 1);
    }

    static void Main()
    {
         string a, b;
         Split ("this is a test", out a, out _);
         Console.WriteLine (a);                      
                   
    }
}

Result

You can include multiple discards in a single call.

Test(out _, out _, out _, out int x, out _, out _, out _);

The compiler would not allow you to use underscore if a real underscore variable is in scope:

string _;
Split ("this is a test", out string a, _);   // Will not compile

Related Topic