Use ThrowHelper methods (ex. ArgumentException.ThrowIfNull) on your elderly .NET project
This package uses Extension members feature on C# 14.
Please Add below on your .csproj or Directory.Build.props.
<PropertyGroup>
<LangVersion>14</LangVersion>
</PropertyGroup>dotnet add package Nogic.ThrowHelperExtensionsnamespace Samples;
public class Sample
{
public string Value1 { get; }
public Sample(string value1)
{
// On .NET 6.0 or higher, it calls `ArgumentNullException.ThrowIfNull` directly.
// On others, it calls `System.ExceptionPolyfills.ThrowIfNull` polyfill via extension members.
ArgumentNullException.ThrowIfNull(value1);
this.Value1 = value1;
}
}ArgumentException.ThrowIfNullOrEmpty(string?, string?)ArgumentException.ThrowIfNullOrWhiteSpace(string?, string?)ArgumentNullException.ThrowIfNull(object?, string?)ArgumentNullException.ThrowIfNull(void*, string?)- Set
AllowUnsafeBlockstotruein your project file to use this overload.
- Set
ObjectDisposedException.ThrowIf(bool, object)ObjectDisposedException.ThrowIf(bool, Type)ArgumentOutOfRangeException.ThrowIfEqual<T>(T, T, string?)ArgumentOutOfRangeException.ThrowIfGreaterThan<T>(T, T, string?) where T : IComparable<T>ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual<T>(T, T, string?) where T : IComparable<T>ArgumentOutOfRangeException.ThrowIfLessThan<T>(T, T, string?) where T : IComparable<T>ArgumentOutOfRangeException.ThrowIfLessThanOrEqual<T>(T, T, string?) where T : IComparable<T>ArgumentOutOfRangeException.ThrowIfNegative<T>(T, string?) where T : INumberBase<T>1ArgumentOutOfRangeException.ThrowIfNegativeOrZero<T>(T, string?) where T : INumberBase<T>1ArgumentOutOfRangeException.ThrowIfNotEqual<T>(T, T, string?)ArgumentOutOfRangeException.ThrowIfZero<T>(T, string?) where T : INumberBase<T>1
- Except for
ArgumentNullException.ThrowIfNull, exception messages are not localized. - Unlike .NET 8.0 and 9.0, these methods do not have
IEquatable<T>constraint on type parameterT. (based on .NET 10.0+ source code)ArgumentOutOfRangeException.ThrowIfEqual<T>(T, T, string?)ArgumentOutOfRangeException.ThrowIfNotEqual<T>(T, T, string?)
- The generated class
System.ExceptionPolyfillsisinternal.
By default, this generator will generate necessary attribute types. (ex. DoesNotReturnAttribute)
If you want to disable attribute generation (for example, use other generator like PolySharp), you can set the following MSBuild property in your project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ThrowHelperExtensionsGenerateAttributes>false</ThrowHelperExtensionsGenerateAttributes>
</PropertyGroup>
</Project>Footnotes
-
INumberBase<T>is not available in .NET 6.0 or below (including .NET Standard 2.0). So, this method only has overloads for the built-in numeric types. (byte,sbyte,short,ushort,int,uint,long,ulong,float,double,decimal,nint,nuint,char) ↩ ↩2 ↩3