Skip to content

CA1859 incorrectly being raised on a public property #50957

@StevePy

Description

@StevePy

CA1859 is intended to optimize private members that would be better served using concrete declarations instead of interfaces or abstract base classes. However, the following scenario incorrectly gets flagged with CA1859:

public ISomething Something { private get; set; } = new Something();

This isn't likely a common scenario, probably a bit pedantic but allowed. It is a scenario I use in Entities for non-injected dependencies, for example the HtmlSanitizer (Ganss.Xss)

public IHtmlSanitizer Sanitizer { private get; set; } = new HtmlSanitizer();

public string Detail 
{ 
    get => Sanitizer.Sanitize(field);
    protected set => field = Sanitizer.Sanitize(value);
}

public void UpdateDetails(string details)
{
    ArgumentException.ThrowIfNullOrEmpty(details, nameof(details));

    var result = Sanitizer.Sanitize(details).Truncate(DetailLength);
    if (!result.IsSuccessful) throw new ArgumentException("The details value could not be truncated.");

    Detail = result.TruncatedText!;

    if (!result.IsTruncated && Extended != null)
        Extended = null;
    else
        (Extended ??= new EmployeeEnquiryExtended(result)).UpdateDetail(result);
}

For tests I want to ensure that updating the detail is sanitized so I will use the public setter to inject a Mock. The getter is private. EF constructed entities use a default constructor so I don't want to mess with trying to inject dependencies when the above works just fine.

Desired behaviour: CA1859 should only apply provided the property is fully private. It appears to only consider the getter. Marking the getter public or protected removes the warning. Protected is not an option if the class is marked as sealed without triggering CS0628. In my case I the getter can be marked protected to remove the warning instead of disabling in-line.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions