I have some C# code that loves to create properties that have setters but no getters. To me this seems like an anti-pattern, but am I missing something?
public List<SiteVisitSummary> DataSource {
set {
// crazy logic here
}
}
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.
Fields can be marked as public, private, protected, internal, protected internal, or private protected. These access modifiers define how users of the type can access the fields. For more information, see Access Modifiers. A field can optionally be declared static.
I don't know if I'd call it an anti-pattern or not. I think the important thing to realize is that the property in your example is essentially a method, disguised as a property. For this reason it's unintuitive, and I'd generally avoid it. To me this looks a lot more natural:
public void SetDataSource(IEnumerable<SiteVisitSummary> dataSource)
{
// crazy logic here
}
One fairly reasonable case I have seen made for set-only properties is when there are several properties grouped together such that setting all to a single value is a reasonable thing to do (but obviously, getting all as one value doesn't make sense). For example:
class Polyhedron
{
public int Height { get; set; }
public int Width { get; set; }
public int Depth { get; set; }
public int AllDimensions
{
set { Height = Width = Depth = value; }
}
}
It could be useful for Dependency Injection, where instead of using a constructor for the injection you are using properties.
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