C# 7.3 Relational Pattern to check nullable type
17 March 2022
Let’s look at traditional way first, lets say we have a nullable integer and we need to write something on Console If it’s value greater then zero.
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Please enter a number > 0!");
string inputLine = Console.ReadLine();
int? myInput = null;
if (!int.TryParse(inputLine, out int parsedInput))
{
Console.WriteLine("Please enter a valid number!");
continue;
}
myInput = parsedInput;
if (!IsValidNumber(myInput))
{
Console.WriteLine("Nope not a valid number!");
continue;
};
}
Console.ReadLine();
}
First we asked user to enter a number, then we tried to parse the string input line to integer. Now lets define a method that checks the integer number!
static bool IsValidNumber(int? input)
{
return input.HasValue && input.Value > 0;
}
It looks fine. But with C# 7.3 we can use relational pattern and we can avoid using HasValue and Value together on our conditions anymore. Let’s change it with relational pattern!
static bool IsValidNumber(int? input)
{
return input is > 0;
}
Looks pretty and clean 🙂