Skip to content

Use ThrowHelper methods (ex. `ArgumentException.ThrowIfNull`) on your elderly .NET project

License

Notifications You must be signed in to change notification settings

nogic1008/ThrowHelperExtensions

Repository files navigation

ThrowHelperExtensions

NuGet (stable version) GitHub releases (including pre-releases) .NET CI codecov CodeFactor License

Use ThrowHelper methods (ex. ArgumentException.ThrowIfNull) on your elderly .NET project

Usage

1. Set LangVersion to C# 14

This package uses Extension members feature on C# 14.

Please Add below on your .csproj or Directory.Build.props.

<PropertyGroup>
  <LangVersion>14</LangVersion>
</PropertyGroup>

2. Add Package

dotnet add package Nogic.ThrowHelperExtensions

3. Use throw helpers

namespace 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;
    }
}

API

Limitations

  • 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 parameter T. (based on .NET 10.0+ source code)
    • ArgumentOutOfRangeException.ThrowIfEqual<T>(T, T, string?)
    • ArgumentOutOfRangeException.ThrowIfNotEqual<T>(T, T, string?)
  • The generated class System.ExceptionPolyfills is internal.

Options

ThrowHelperExtensionsGenerateAttributes

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

  1. 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

About

Use ThrowHelper methods (ex. `ArgumentException.ThrowIfNull`) on your elderly .NET project

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors 3

  •  
  •  
  •  

Languages