4

I was look at somebody else's code and came across this piece of code

private string _deviceName { get; set; }
private string _deviceAlias { get; set; }

My thinking is that those automatic properties for private variables are unnecessary. Am I right in thinking so ?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
devcoder
  • 1,675
  • 2
  • 21
  • 28
  • possible duplicate of [What are the benefits of using properties internally?](http://stackoverflow.com/questions/2884715/what-are-the-benefits-of-using-properties-internally) – nawfal Jun 03 '13 at 17:52

2 Answers2

8

My thinking is that those automatic properties for private variables are unnecessary. Am I right in thinking so ?

They aren't necessary, but they also don't really hurt anything. That being said, they don't really help anything either, as they're purely an implementation detail, so switching from a field to a property later wouldn't be a breaking change.

The only real reason to potentially do this would be if you knew, in the future, you would want custom logic on get or set, and you were using something that required the syntax to be different for properties, such as reflection. In this case, making them auto-properties now would prevent any need for changing the code later.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • They do help, But aren't necessary. They are essential for input validation. Input validation is often overlooked at this level of programming. You usually don't consider that other programmers need to be validated as well. – ZnArK Jun 26 '12 at 17:17
  • 1
    @ZnArK, "input validation" is a concern for neither private fields *nor* private properties. – Kirk Woll Jun 26 '12 at 17:19
  • @KirkWoll This is obviously debatable. I guess it comes down to your own style and level of attention to detail. :) http://programmers.stackexchange.com/a/64930 – ZnArK Jun 26 '12 at 17:24
  • 2
    @ZnArK, you are *continuing* to confuse validating the public surface of an API with validating the internal implementation details. By your logic, if you had `private string foo { get; set; }` and `public string Foo { get { return foo; } set { foo = value; } }`: you are suggesting validating at both `foo.set` and `Foo.set`, which is complete nonsense. – Kirk Woll Jun 26 '12 at 17:28
0

Its just that instead of creating a variable, you created a property on which in future you want some custom work while setting and retrieving value.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208