Skip to content

SYSLIB1045 Use GeneratedRegex auto-correct causes CS0756 multiple defining declarations #77409

@timmydo

Description

@timmydo

Description

If A.cs and B.cs both have public partial class C and both have methods needing a new Regex() -> [GeneratedRegex] replacement, the source generator fix puts MyRegex() in both files, which causes a compilation error. I invoked the fix by running dotnet-format project.csproj --diagnostics SYSLIB1045 --no-restore.

Reproduction Steps

using System.Text.RegularExpressions;

namespace RegexReplacement
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }

    internal partial class C
    {
        public static Regex A()
        {
            var r = new Regex("abc");
            return r;
        }
    }

    internal partial class C
    {
        public static Regex B()
        {
            var r = new Regex("def");
            return r;
        }
    }
}

Expected behavior

using System.Text.RegularExpressions;

namespace RegexReplacement
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }

    internal partial class C
    {
        public static Regex A()
        {
            var r = MyRegex();
            return r;
        }

        [GeneratedRegex("abc")]
        private static partial Regex MyRegex();
    }

    internal partial class C
    {
        public static Regex B()
        {
            var r = MyRegex();
            return r;
        }

        [GeneratedRegex("def")]
        private static partial Regex MyRegex2();
    }
}

Actual behavior

using System.Text.RegularExpressions;

namespace RegexReplacement
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }

    internal partial class C
    {
        public static Regex A()
        {
            var r = MyRegex();
            return r;
        }

        [GeneratedRegex("abc")]
        private static partial Regex MyRegex();
    }

    internal partial class C
    {
        public static Regex B()
        {
            var r = MyRegex();
            return r;
        }

        [GeneratedRegex("def")]
        private static partial Regex MyRegex();
    }
}

Regression?

no

Known Workarounds

manual fix

Configuration

$ dotnet-format --version
7.0.351204+c1136d16ab588f45727fe908212b90578edc2aff

7.0.100-rc.1.22431.12 [C:\Program Files\dotnet\sdk]

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions