CA1044: Properties should not be write only

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

TypeName PropertiesShouldNotBeWriteOnly
CheckId CA1044
Category Microsoft.Design
Breaking Change Breaking

Cause

The public or protected property has a set accessor but does not have a get accessor.

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 is strongly recommended that you do not suppress a warning from this rule.

Example

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

using System;

namespace DesignLibrary
{
   public class BadClassWithWriteOnlyProperty
   {
      string someName;

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

   public class GoodClassWithReadWriteProperty
   {
      string someName;

      public string Name 
      { 
         get 
         { 
            return someName; 
         } 
         set 
         { 
            someName = value; 
         } 
      }
   }
}
Imports System

Namespace DesignLibrary

   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

      Dim someName As String

      Property Name As String
         Get 
            Return someName
         End Get 

         Set 
            someName = Value
         End Set 
      End Property

   End Class

End Namespace