Skip to content

PolyFill Exception.Throw... methods using C# 14 static extension methods. #132

@sonnemaf

Description

@sonnemaf

Are there plans for adding the ...Exception.Throw...() methods to PolySharp. With C# 14 we can add static extension methods to classes. This would allow a lot of extra methods to be added. Not sure if this is the correct place because it would require C# 14. Maybe only generate this code if the LangVersion is 14+.

Maybe it could be added to CommunityToolkit.Diagnostics.

Example

Suppose this is a .NET Standard class Library. The C# 14 static extensionmethod ThrowIfNull is added to the ArgumentNullException.

using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

namespace ClassLibrary1;

public class Class1 {

    public static void Foo(string a) {
        ArgumentNullException.ThrowIfNull(a);
    }
}

public static class PolyExceptions {

    extension(ArgumentNullException) {

        public static void ThrowIfNull([NotNull] object? argument,
            [CallerArgumentExpression(nameof(argument))] string? paramName = null) {

            if (argument is null) {
                throw new ArgumentOutOfRangeException(paramName);
            }
        }
    }
}

Used this csproj file

<Project Sdk="Microsoft.NET.Sdk">

	<PropertyGroup>
		<TargetFramework>netstandard2.0</TargetFramework>
		<LangVersion>preview</LangVersion>
		<Nullable>enable</Nullable>
		<ImplicitUsings>true</ImplicitUsings>
	</PropertyGroup>

	<ItemGroup>
	  <PackageReference Include="PolySharp" Version="1.15.0">
	    <PrivateAssets>all</PrivateAssets>
	    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
	  </PackageReference>
	</ItemGroup>

</Project>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions