I don't know why I started thinking about this, but now I can't seem to stop.
In C# - and probably a lot of other languages, I remember that Delphi used to let you do this too - it's legal to write this syntax:
class WeirdClass { private void Hello(string name) { Console.WriteLine("Hello, {0}!", name); } public string Name { set { Hello(name); } } }
In other words, the property has a setter but no getter, it's write-only.
I guess I can't think of any reason why this should be illegal, but I've never actually seen it in the wild, and I've seen some pretty brilliant/horrifying code in the wild. It seems like a code smell; it seems like the compiler should be giving me a warning:
CS83417: Property 'Name' appears to be completely useless and stupid. Bad programmer! Consider replacing with a method.
But maybe I just haven't been doing this long enough, or have been working in too narrow a field to see any examples of the effective use of such a construct.
Are there real-life examples of write-only properties that either cannot be replaced by straight method calls or would become less intuitive?
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.
Consider using a property if the member represents a logical attribute of the type. Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.
Defining a write-only class in Java If we made a class write-only then we can modify the properties or data member value of the class. If we made a class write-only then we can only write the properties or data members value of the class.
Code Analysis (aka FxCop) does give you a diagnostic:
CA1044 : Microsoft.Design : Because property 'WeirdClass.Name' is write-only, either add a property getter with an accessibility that is greater than or equal to its setter or convert this property into a method.
My first reaction to this question was: "What about the java.util.Random#setSeed method?"
I think that write-only properties are useful in several scenarios. For example, when you don't want to expose the internal representation (encapsulation), while allowing to change the state of the object. java.util.Random is a very good example of such design.
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