The optional do functionality allows for an action to be performed on an optional value only if the value is present. This avoids having to check for null or missing values before performing actions on them.
Example 1: Here's an example where we want to print the length of a string, but we're not sure if the string is null or not:
string str = null; str?.Length.Do(Console.WriteLine); //no output, since the string is null
Example 2: In this example, we have a list of students, and we want to find the first student with a particular last name, but we're not sure if the list is null or if the student we're looking for exists:
List students = null; students?.FirstOrDefault(s => s.LastName == "Smith").Do(s => Console.WriteLine(s.FirstName)); //no output, since the list is null
students = new List { new Student { FirstName = "John", LastName = "Doe" }, new Student { FirstName = "Jane", LastName = "Smith" }, new Student { FirstName = "Bob", LastName = "Johnson" } };
This functionality is part of the C# 8.0 language features and does not require any additional package library.
C# (CSharp) Optional.Do - 23 examples found. These are the top rated real world C# (CSharp) examples of Optional.Do extracted from open source projects. You can rate examples to help us improve the quality of examples.