Skip to content

Instantly share code, notes, and snippets.

@BenjaminAbt
Last active September 30, 2021 15:55
Show Gist options
  • Save BenjaminAbt/29e711db415f6db4eb13f1940e9c9add to your computer and use it in GitHub Desktop.
Save BenjaminAbt/29e711db415f6db4eb13f1940e9c9add to your computer and use it in GitHub Desktop.
Better C# ArgumentNullExceptions
// 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