Search code examples
c#.netvb.netcoding-style

WriteOnly Property or Method?


Is there a particular scenario where a WriteOnly property makes more sense then a method? The method approach feels much more natural to me.

What is the right approach?

Using Properties:

Public WriteOnly Property MyProperty As String
   Set(ByVal value as String)
      m_myField = value
   End Set
End Property
public string MyProperty
{
   set{ m_myField = value;}
}

Using Methods:

Public Sub SetMyProperty(ByVal value as String)
   m_myField = value
End Sub
public void SetMyProperty(string value)
{
   m_myField = value;
}

EDIT Just to clarify I am referring to "WriteOnly" properties.


Solution

  • I think a property indicates something that can be read-only or read/write. The behaviour of a write-only property is not obvious so I avoid creating them.

    As an example, setting a list of values in a drop-down on a view and accessing the selected item:

    public interface IWidgetSelector
    {
      void SetAvailableWidgets(string[] widgets);
    
      string SelectedWidget { get; set; }
    }
    

    Makes more sense than:

    public interface IWidgetSelector
    {
      string[] AvailableWidgets { set; }
    
      string SelectedWidget { get; set; }
    }