Simple property/field question

olsonpm

Well-known member
Joined
Aug 24, 2010
Messages
46
Programming Experience
Beginner
So I'm just trying to understand why someone would want to use the shorthand property instantiation

Public Property CarModel As String <-- property

as opposed to

Public CarModel As String <-- variable
 
If you can tell me how this does not apply to public shorthand properties, then I will believe you.

c# - Are protected members/fields really that bad? - Stack Overflow
"Since a field is totally uncontrolled, putting it "out in the wild" opens your class and classes that inherit from or interact with your class to higher bug risk. There is no way to know when a field changes, no way to control who or what changes it."
 
Have you read this: Auto-Implemented Properties (Visual Basic)
As this explains, and I also have explained to you many times now, the auto-implemented property produce exactly code the same as a regular property declaration.
You can't compare a field to a property because they are two completely different things.
 
What you are trying to tell me, is that properties don't allow me to do the following

VB.NET:
public class main

  public sub main()
    dim a as new Apple("Red")
    a.Color = "Car"
  end sub

end class

public class Apple

  Public Property Color() As String

  public sub new(color_ as String)
    Color = color_
  end sub
end class

_Obviously_ you can change the color property to your heart's content. It is a bad coding practice because Apple should be in charge of it's state after instantiation, and is exactly why they advise against public fields. It doesn't matter whether or not a private variable is hidden under the property.
 
Does that honestly not make sense to you?
No, not even slightly. You still seem to think a field and property is the same thing, which they are not. Perhaps if you think of fields as containers, and properties as container transport vehicles, that will help you understand the difference? A property can not hold a value, it can only transport a value to and from a field.
 
So the above code I just wrote wouldn't be considered bad practice because it's a property? Because Color is a transport vehicle for the private field 'color'...
 
Exposing object state by properties is considerer the good practice, yes.
 
Back
Top