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.
A write only property is a property that we can assign a value to but can't get that value because that property doesn't have a get accessor. For example we have a Person class that has the property FirstName that has a set accessor but doesn't have a get accessor so it is a write only property.
You can use WriteOnly only at module level. This means the declaration context for a WriteOnly property must be a class, structure, or module, and cannot be a source file, namespace, or procedure. You can declare a property as WriteOnly , but not a variable.
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color. Properties can be set at design time by using the Properties window or at run time by using statements in the program code. Object.
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; }
}
For what it's worth, the Microsoft Framework Design Guidelines (as embodied in their FxCop tool) discourage Write-Only Properties and flag their presence as an API design issue, due to the unintuitiveness of that approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With