Search code examples
c#linqpad

Linqpad use of discard (_ = underscore) throws Error CS0246 - the type or namespace name '_' could not be found


I want to learn about named tuples and discard.

Based on C# 7.0: Tuples Explained (msdn-magazine 2017-08) i created this program

void Main()
{

(string firstname, _, int age) user = ("surfmuggle", "discard this", 15);
user.Dump();
}

but it throws

CS0246 The type or namespace name '_' could not be found (press F4 to add a using directive or assembly reference)

Question

Thanks

A screen of the program

Linqpad 6 program


Solution

  • This is unrelated to LINQPad - you'll get the same error in Visual Studio.

    The problem is that you're trying to use C#'s discards in a context in which they're unsupported. From the documentation:

    In C# 7.0, discards are supported in assignments in the following contexts:

    • Tuple and object deconstruction.
    • Pattern matching with is and switch.
    • Calls to methods with out parameters.
    • A standalone _ when no _ is in scope.

    Your example would work in a deconstruction context:

    (string firstname, _, int age) = ("surfmuggle", "discard this", 15);
    firstname.Dump();
    age.Dump();