Skip to content

System.Text.RegularExpressions.Generator doesn't support multi-targeted projects, even if GeneratedRegexAttribute is shimmed #104212

Open
@madelson

Description

@madelson

Description

In multitargeted projects (e.g. netstandard2.0 + .net8.0), the regex analyzer often suggests a refactor to use GeneratedRegex.

However, GeneratedRegex isn't compatible with older frameworks, both because the attribute does not exist and because the source generator doesn't run on the older frameworks.

It would be nice if the generator would simply emit a cached field for frameworks that don't support full source generation, just like it does today for older language versions. The user would still have to shim the attribute themselves, but this is easy to do, could be done by the codefix, or could probably even be part of the generator itself.

This would allow multi-targeted libraries to take advantage of generated regex performance for the builds that target newer frameworks while still supporting netstandard2.0.

Reproduction Steps

Try to use GeneratedRegex in a multi-targeted project

Expected behavior

It would be nice if this "just worked", but at least it should stop suggesting a codefix which breaks the build.

Actual behavior

Generator does not run

Regression?

No

Known Workarounds

I can manually fork the generation with #if:

#if NET
    [StringSyntax(StringSyntaxAttribute.Regex)]
#endif
    private const string MyRegexPattern = @"a.*b";

#if !NET
    private static Regex? MyRegexCache;
    private static Regex MyRegex() => MyRegexCache ??= new(MyRegexPattern);
#else
    [GeneratedRegex(MyRegex)]
    private static partial Regex MyRegex();
#endif

Configuration

.NET 8

Other information

n/a

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions