It strikes me that Properties in C# should be use when trying to manipulate a field in the class. But when there’s complex calculations or database involved, we should use a getter/setter.
Is this correct?
When do you use s/getter over properties?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The .NET design guidelines provide some answers to this question in the Properties vs. Methods section.
Basically, properties have the same semantics as a field. You shouldn’t let a property throw exceptions, properties shouldn’t have side effects, order shouldn’t matter, and properties should return relatively quickly. If any of those things could happen, it’s better to use a method. The guidelines also recommend using methods for returning arrays.
When deciding whether to use a property or method, it helps if I think of it like a field. I think about the behavior of the property and ask myself, ‘If this were a field on the class, would I be surprised if it behaved the way it does?’ Consider, for example, the TcpClient.GetStream method. It can throw several exceptions based on if the connection is made, and it’s important that the TcpClient is configured before you try to get the stream. Because of this, it is a Get method rather than a property.
If you take a good look at the design guidelines, you’ll see that it’s usually not a matter of preference; there’s good reasons to use methods instead of properties in certain cases.