...

/

Replace a Set of Choices with FirstOrDefault

Replace a Set of Choices with FirstOrDefault

Use the FirstOrDefault method to replace a chain of conditionals.

How to Refactor a chain of conditionals with FirstOrDefault

When we need to find a value between multiple choices, we write consecutive if statements to check for a valid result every time.

For example, let’s find the next film to watch from one of three sources: the latest releases in cinemas, our friends’ recommendations, and the all-time classics.

Press + to interact
using System;
namespace MovieCatalog
{
internal class Program
{
public static void Main(string[] args)
{
// Let's find the next movie to watch
var nextMovie = FindLastestRelease();
if (nextMovie == null)
nextMovie = FindFriendsRecommendation();
if (nextMovie == null)
nextMovie = FindClassic();
if (nextMovie != null)
Console.WriteLine($"{nextMovie.Name}");
else
Console.WriteLine("No movies to watch");
}
private static Movie FindLastestRelease()
{
return null;
}
private static Movie FindFriendsRecommendation()
{
return new Movie
{
Name = "Taxi Driver",
Genre = Genre.Drama
};
}
private static Movie FindClassic()
{
return new Movie
{
Name = "Spirited Away",
Genre = Genre.Fantasy
};
}
}
internal class Movie
{
public string Name { get; set; }
public Genre Genre { get; set; }
}
internal enum Genre
{
Comedy,
Action,
Drama,
War,
Fantasy
}
}

Notice that after we called a ...