Pattern: Use of nullable struct for ArgumentNullException.ThrowIfNull
Issue: -
When a nullable struct, for example, int?
or Guid?
, is passed to ArgumentNullException.ThrowIfNull
, it's boxed to an object, causing a performance penalty.
Example of incorrect code:
static void Print(int? value)
{
ArgumentNullException.ThrowIfNull(value);
Console.WriteLine(value.Value);
}
Example of correct code:
static void Print(int? value)
{
if (!value.HasValue)
{
throw new ArgumentNullException(nameof(value));
}
Console.WriteLine(value.Value);
}