Skip to content

Instantly share code, notes, and snippets.

@GReturn
Last active September 3, 2023 12:31
Show Gist options
  • Save GReturn/91834fbc99fe348d0302f509ab85511a to your computer and use it in GitHub Desktop.
Save GReturn/91834fbc99fe348d0302f509ab85511a to your computer and use it in GitHub Desktop.
C# - Null Checking Using C# 7 Discards and the C# 9 Way
/**********************************************************************************
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