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.

 1using System;
 2
 3namespace DiscardLambdaParameters
 4{
 5    class Program
 6    {
 7        static void Main(string[] args)
 8        {
 9            var random = new Random(1); // seed
10         
11            Func<int, (int, int, int)> GetThreeNumbersWithMaxOfXLambda = maxValue => 
12            {
13                return (random.Next(maxValue), random.Next(maxValue), random.Next(maxValue));
14            };
15
16            var (a, b, c) = GetThreeNumbersWithMaxOfXLambda(10); // no discard
17            Console.WriteLine($"a = {a}, b = {b}, c = {c}");
18
19            var (d, e, _) = GetThreeNumbersWithMaxOfXLambda(100); // discard one
20            Console.WriteLine($"d = {d}, e = {e}");
21
22            var (g, _, _) = GetThreeNumbersWithMaxOfXLambda(100); // discard two
23            Console.WriteLine($"g = {g}");
24        }
25    }
26}
 
That’s all there is too it.

comments powered by Disqus

Related