Last active
September 30, 2021 15:55
-
-
Save BenjaminAbt/29e711db415f6db4eb13f1940e9c9add to your computer and use it in GitHub Desktop.
Better C# ArgumentNullExceptions
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
// C# 5 | |
public void MyMethod(string name) | |
{ | |
if (name == null) throw new ArgumentNullException("name", "name cannot be null."); | |
} | |
// C# 6 - nameof() to avoid magic strings | |
public void MyMethod(string name) | |
{ | |
if (name == null) throw new ArgumentNullException(nameof(name), $"{nameof(name)} cannot be null."); | |
} | |
// C# 7 - null coalescing operator | |
public void MyMethod(string name) | |
{ | |
_ = name ?? throw new ArgumentNullException(nameof(name), $"{nameof(name)} cannot be null."); | |
} | |
// C# 9 - null parameter checking | |
public void MyMethod(string! name) // <<< Null Parameter checking via ! | |
{ | |
// runtime check still recommended, but compiler check with null parameter checking. | |
} | |
// C# 10 - simple static method | |
public void MyMethod(string name) | |
{ | |
ArgumentNullException.ThrowIfNull(name, nameof(name)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment