CA1044: Properties should not be write only

Property Value
Rule ID CA1044
Title Properties should not be write only
Category Design
Fix is breaking or non-breaking Breaking
Enabled by default in .NET 8 No

Cause

A property has a set accessor but not a get accessor.

By default, this rule only looks at externally visible types, but this is configurable.

Rule description

Get accessors provide read access to a property and set accessors provide write access. Although it is acceptable and often necessary to have a read-only property, the design guidelines prohibit the use of write-only properties. This is because letting a user set a value and then preventing the user from viewing the value does not provide any security. Also, without read access, the state of shared objects cannot be viewed, which limits their usefulness.

How to fix violations

To fix a violation of this rule, add a get accessor to the property. Alternatively, if the behavior of a write-only property is necessary, consider converting this property to a method.

When to suppress warnings

It's recommended that you don't suppress warnings from this rule.

Configure code to analyze

Use the following option to configure which parts of your codebase to run this rule on.

You can configure this option for just this rule, for all rules it applies to, or for all rules in this category (Design) that it applies to. For more information, see Code quality rule configuration options.

Include specific API surfaces

You can configure which parts of your codebase to run this rule on, based on their accessibility. For example, to specify that the rule should run only against the non-public API surface, add the following key-value pair to an .editorconfig file in your project:

dotnet_code_quality.CAXXXX.api_surface = private, internal

Example

In the following example, BadClassWithWriteOnlyProperty is a type with a write-only property. GoodClassWithReadWriteProperty contains the corrected code.

Imports System

Namespace ca1044

    Public Class BadClassWithWriteOnlyProperty

        Dim someName As String

        ' Violates rule PropertiesShouldNotBeWriteOnly.
        WriteOnly Property Name As String
            Set
                someName = Value
            End Set
        End Property

    End Class

    Public Class GoodClassWithReadWriteProperty

        Property Name As String

    End Class

End Namespace
public class BadClassWithWriteOnlyProperty
{
    string? _someName;

    // Violates rule PropertiesShouldNotBeWriteOnly.
    public string? Name
    {
        set
        {
            _someName = value;
        }
    }
}

public class GoodClassWithReadWriteProperty
{
    public string? Name { get; set; }
}