C#9 - FP linked to private constructors and the new terse new() syntax?

There appears to be a bug with private constructors and the new terse new() syntax ( Target-typed new leading to
Code Smell: Remove the unused private constructor

public class Foo
    {
        private Foo()
        {
        }
        public static Foo Create()
        {
            return new();
        }
    }

Hi @tsc_templafy,

I’m not able to reproduce the issue with your code sample. Are you getting S1144 there?

It appears I simplified the example a bit too much. With a parameterless ctor it does not complain, however these two examples fail:

S3453:

public class Foo
{
	public static readonly Foo Instance = new();

	private Foo()
	{
	}

	public bool IsActive => true;
}

S1144 and S3453:

public class Bar
{
    private Bar(string name)
    {
        Name = name;
    }

    public string Name { get; }

    public static Bar Create()
    {
        return new("John Doe");
    }
}

Hi @tsc_templafy,

Thank you for the new version, I’m able to reproduce those.

Our analyzers can now scan C# 9 projects, but rules don’t support new C# 9 syntax yet. Support for Target-typed new will be added in MMF-2225.

I’ve documented your examples in our tests and added the rules to the MMF to be sure we cover it during development phase.

Thank you

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.