Last active
September 3, 2023 12:31
-
-
Save GReturn/91834fbc99fe348d0302f509ab85511a to your computer and use it in GitHub Desktop.
C# - Null Checking Using C# 7 Discards and the C# 9 Way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************************************************** | |
Discards (_) do not take up memory. These were introduced in C# 7. | |
This code evaluates if variable name has a value then return. Else, throw ANE. | |
Additionally, it uses the null-coalescing operator for null checks. | |
*/ | |
public static int CountNumberOfSInName(string name) | |
{ | |
_ = name ?? throw new ArgumentNullException(nameof(name)); | |
return name.Count(c => char.ToLower(c).Equals('s')); | |
} | |
/********************************************************************************** | |
In the case when deciding to use the value of variable 'name' instead of assigning | |
it to a discard, you can do this: | |
*/ | |
private readonly string _name; | |
public static int CountNumberOfSInName(string name) | |
{ | |
_name = name ?? throw new ArgumentNullException(nameof(name)); | |
return _name.Count(c => char.ToLower(c).Equals('s')); | |
} | |
/********************************************************************************** | |
The codes above sacrifices readability. | |
C# 9 allows the combination of the "is" expression and the "not" logical pattern. | |
You can do the following for null checks that preserves readability: | |
*/ | |
if (name is null) { } | |
else | |
// or: | |
if (name is not null) { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment