Skip to content

Lambda discard parameters C# 9.0correctnessreadability

Signify no interest in a parameter to a lambda.

C# 7.0 added discards for out arguments, deconstruction and patterns. C# 9.0 extends this to the parameters of lambdas and anonymous methods, so you can signal that you are not interested in a parameter which is required by the signature.

Without this, code analysis tools stumble trying to decide if an unused parameter was intentional or should be removed.

Discard parameters allow you to name any such parameter _ to signal that this omission is intentional.

Code ​

csharp
Action<string, int> logger = (string message, int indent)
    => Log(new string(' ', indent) + message);

if (disableLogging)
    logger = (_, _) => { };

logger("OK", 0);
csharp
Action<string, int> logger = (string message, int indent)
    => Log(new string(' ', indent) + message);

if (disableLogging)
    logger = (message, indent) => { };

logger("OK", 0);

Notes ​

  • A lone _ is still an ordinary parameter named _ for backward compatibility; only two or more _ parameters are treated as discards

More information ​

Powered by Intracia