Simple Example of C# 9 Lambda Discards

This is a very quick post showing how to use the new Lambda discards feature of C# 9.

The general idea is to not assign a variable to something you are never going to use.

For example, if you have a method that returns three random numbers, but you only need two of them, there is no need to assign the third. This will make your code neater, and probably improve performance as there is one less variable to garbage collect.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;

namespace DiscardLambdaParameters
{
    class Program
    {
        static void Main(string[] args)
        {
            var random = new Random(1); // seed
         
            Func<int, (int, int, int)> GetThreeNumbersWithMaxOfXLambda = maxValue => 
            {
                return (random.Next(maxValue), random.Next(maxValue), random.Next(maxValue));
            };

            var (a, b, c) = GetThreeNumbersWithMaxOfXLambda(10); // no discard
            Console.WriteLine($"a = {a}, b = {b}, c = {c}");

            var (d, e, _) = GetThreeNumbersWithMaxOfXLambda(100); // discard one
            Console.WriteLine($"d = {d}, e = {e}");

            var (g, _, _) = GetThreeNumbersWithMaxOfXLambda(100); // discard two
            Console.WriteLine($"g = {g}");
        }
    }
}
 
That’s all there is too it.

comments powered by Disqus

Related