Dumb question of the day

Last post 10-30-2003 6:37 PM by jbrinkman. 2 replies.

Sort Posts:

  • Dumb question of the day

    10-30-2003, 4:15 PM
    • Contributor
      6,887 point Contributor
    • mathisjay
    • Member since 12-05-2002, 11:34 AM
    • Atlanta
    • Posts 1,376
    I know this is newbie but I can't find the answer...


    What is the difference in declaring something as a variable vs. as a property?

    IE.

    Public myNum as Integer

    or

    private _myNum as Integer
    Public Property myNum
    Get ..
    Set...

    Any help?
  • Re: Dumb question of the day

    10-30-2003, 4:59 PM
    • Participant
      915 point Participant
    • Rex
    • Member since 06-14-2002, 6:53 PM
    • Spuzzum
    • Posts 183



    Functionally there's no difference if your Property contains no extra code; but a Property gives you more flexibility by having the added capability to have code execute before the "Get" returns or the "Set" completes. You can do validations or calculation or other logic. Your "Class Level Fields" do not support this capability.


    It takes a pretty big dog to weigh a thousand pounds.
  • Re: Dumb question of the day

    10-30-2003, 6:37 PM
    • Star
      9,820 point Star
    • jbrinkman
    • Member since 06-18-2002, 2:28 PM
    • Posts 1,962
    • TrustedFriends-MVPs
    If you look at your code from a pure Object Oriented approach, Properties enforce the OO principle of encapsulation. By hiding your class member variables behind a Property, you hide the implementation details from the user of that class. For example: Your original code was:
    Public MyNum as string
    and you wanted to change it to store the variable as an integer instead, you would need to change every line of code that referenced that variable (assume Option Strict).

    If instead you had used:
    Private _MyNum as string
    

    Property MyNum() as string
    Get...
    Set...
    End Property


    Now all the code that knows how this data is stored is isolated to this one place. You are free to use an Private storage mechanism and allow the Property Get/Set methods to do the appropriate conversions to/from string to ensure compatability with existing code.

    I try to always expose member variables as properties because it allows me to keep my code consistent and I don't need to worry about future changes to the storage details from affecting any other code.
    Joe Brinkman
Page 1 of 1 (3 items)