int MyProperty { set; }
What\'s the idea for using only setter on property? If we set one property with some value, I guess it\'s very likely to read t
Write-only properties are rare in the Base Class Library, but XmlReaderSettings.XmlResolver is one example. Based on the security note in that topic, I believe the get accessor was omitted to prevent partially trusted code from accessing or tampering with the default resolver.
XmlResolver.Credentials and XmlTextReader.XmlResolver are probably write-only properties for the same reason.
(Strangely, XmlAttribute.InnerText is also a write-only property, but this doesn't seem to be good design.)
Following the above examples, I'd say you should use a write-only property only when a read-write property would otherwise make sense, but you don't want a get accessor for security reasons.
You could of course use a Set
method instead, but a property has the advantage that it can be used in an object initializer, as is commonly done with XmlReaderSettings
.
It doesn't make a whole lot of sense to have an auto-property with only a setter. It can make sense to have a manually implemented property with only a setter that can then set a field used internally, but not visible externally.
Having a set only property is very uncommon, and are often implemented with a set method instead of a property as a set-only property is not expected behavior for most developers.
In fact, it is a compiler error for an auto-implemented property to define a set
without a get
. A set-only property must be manually defined.
A method would make much more sense than a 'write only property' - even if the code did compile. There is an interesting discussion around write only proprties Here
You normally don't create a property like this. As you say, it doesn't have much value.
If you really want to allow only setting a certain value without reading it, then provide a method. That's cleaner.