Results 1 to 25 of 25

Thread: [RESOLVED] Default Property Values

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Sep 2009
    Posts
    115

    Resolved [RESOLVED] Default Property Values

    What is the difference between these two methods for defining property value defaults?

    Code:
        Public intSomeInt As Integer
        Public strSomeString As String
        Public objSomeObject As Object
        Public booTrueFalse As Boolean
    
        Sub New()
            intSomeInt = 100
            strSomeString = "DefaultString"
            objSomeObject = strSomeString
            booTrueFalse = True
        End Sub
    Code:
        Public intSomeInt As Integer = 100
        Public strSomeString As String = "DefaultString"
        Public objSomeObject As Object = strSomeString
        Public booTrueFalse As Boolean = True
    
        Sub New()
            'Constructor code here
        End Sub
    Is there a reason to use one method over the other for defining the default property values in a class?

  2. #2
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 2005
    Location
    Montana
    Posts
    2,993

    Re: Default Property Values

    If you had multiple constructors, you would have a bunch of duplicate code.
    That is the very essence of human beings and our very unique capability to perform complex reasoning and actually use our perception to further our understanding of things. We like to solve problems. -Kleinma

    Does your code in post #46 look like my code in #45? No, it doesn't. Therefore, wrong is how it looks. - jmcilhinney

  3. #3
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Default Property Values

    as Bill said, it could lead to code duplication if you init the values in the constructor. In reality at runtime, the values are assigned when the constructor is called anyway. There is a readability factor when giving them values where declared. You don't have to go look at the constructor to see what values were given by default, you just look at the declarations.

    One other side note is that those are not actually "properties" at all, they are "fields". A property uses property syntax of

    Code:
    Private _someInt as Integer = 100
    Public Property SomeInt() as Integer
       Get
          return _someInt
       End Get
       Set(Value as integer)
          _someInt = value
       End Set
    End Property
    or in VB10 we can now do

    Code:
    Public Property SomeInt as Integer = 100
    and it is the same as the first piece of code I posted.

    The main difference between fields and properties is that properties support databinding and fields do not, and properties can contain validation logic, where fields are just straight variables.

  4. #4
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Default Property Values

    Since we're getting semantic, I should point out that you are talking about initial values, not default values. A default value (only for properties) is the value that the IDE gives your property when you rightclick it in the properties list and select "Reset". You set the default value by using the DefaultValue attribute:
    vb.net Code:
    1. Private _Value As Integer
    2. Private _Visible As Boolean
    3.  
    4. <DefaultValue(5)> _
    5. Public Property Value() As Integer
    6.    Get
    7.       Return _Value
    8.    End Get
    9.    Set(ByVal value As Integer)
    10.       _Value = value
    11.    End Set
    12. End Property
    13.  
    14. 'or
    15.  
    16. <DefaultValue(GetType(Boolean), "True")> _
    17. Public Property Visible() As Boolean
    18.    Get
    19.       Return _Visible
    20.    End Get
    21.    Set(ByVal value As Boolean)
    22.       _Visible= value
    23.    End Set
    24. End Property

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Sep 2009
    Posts
    115

    Re: Default Property Values

    My example code was hastily constructed to illustrate my question.

    For some reason, I was under the impression that it was generally more accepted to put the initial values in the constructor. Not sure why - probably just the examples that I have seen. But, it seemed more cumbersome and error prone this way. Hence, I figured I better ask

    What would be the use for the DefaultValue property, aside from where a property grid may be used? Going back to readability, if all the fields had their initial values set in a declarations section, this would be preferred, correct?

  6. #6
    Fanatic Member Megalith's Avatar
    Join Date
    Oct 2006
    Location
    Secret location in the UK
    Posts
    879

    Re: Default Property Values

    Quote Originally Posted by kleinma
    or in VB10 we can now do

    Code:
    Public Property SomeInt as Integer = 100
    wow i like that and am tempted to go to VS2010 because of it, I have spent hours doing all them return _blah, _blah = blah things in my 2008 classes
    If debugging is the process of removing bugs, then programming must be the process of putting them in.

  7. #7
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Default Property Values

    well you know you could just type the word property and then hit tab in VS2008 to use the snippet feature. It isn't AS good as auto props in VS2010, but it is a close second.

  8. #8
    Fanatic Member Megalith's Avatar
    Join Date
    Oct 2006
    Location
    Secret location in the UK
    Posts
    879

    Re: Default Property Values

    tbh i find the snippet way harder than using class details and a class diagram but yeah this 2010 feature is very useful, the majority of my properties are of the standard type that is shorthand for, but we digress...
    If debugging is the process of removing bugs, then programming must be the process of putting them in.

  9. #9
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Default Property Values

    The new feature in VS2010 still even creates a private backing field with the underscore prefix (you just don't see it in your code).

    You also get databinding support still. So really the only time you need full properties in VS2010 now is when you need logic in your getter/setter, or if you need read only/write only properties.

  10. #10
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Default Property Values

    Quote Originally Posted by wolfpackmars2 View Post
    What would be the use for the DefaultValue property, aside from where a property grid may be used?
    Not much really, except if you created a UserControl / custom control / component that you rely on heavily and want to add some user-friendliness to it. If 'where a property grid may be used' you mean dropping a PropertyGrid control on your form, then I'm not even sure if the DefaultValue attribute can be used, because the PropertyGrid does not show the context menu. I suppose you can add your own context menu, but then I'm not sure how to call the functionality that the Reset feature usually provides.

    So basically it is just to make the design-time easier for your own custom controls.


    Quote Originally Posted by kleinma View Post
    So really the only time you need full properties in VS2010 now is when you need logic in your getter/setter, or if you need read only/write only properties.
    Can't you just use ReadOnly?
    vb.net Code:
    1. Public ReadOnly Property Value() As Integer
    Shouldn't that just create a read-only automated property?

    I think you do need to use full properties if you need different access modifiers on the getter and setter (or is that possible even with auto-implemented properties?).
    If you can't, then I must say I like C#'s way much better:
    csharp Code:
    1. // read-only:
    2. public int Value { get; }
    3.  
    4. // private set; public get:
    5. public int Value { get; private set; }



    That said, I'm not sure how it would be possible to implement this behavior for VB without breaking all formatting rules... Perhaps something like
    vb.net Code:
    1. Public Property Value() As Integer { Get, Private Set }
    2.  
    3. Public Property Value() As Integer With Get, Private Set
    4.  
    5. Public Property Value() As Integer With { Get, Private Set }
    6.  
    7. Public Property Value() As Integer
    8.    Get
    9.    Private Set
    10. End Property
    Meh?

  11. #11
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Default Property Values

    Quote Originally Posted by NickThissen View Post

    Can't you just use ReadOnly?
    vb.net Code:
    1. Public ReadOnly Property Value() As Integer
    Shouldn't that just create a read-only automated property?
    If that were possible, what is that property returning when you call it?

  12. #12
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Default Property Values

    Quote Originally Posted by kleinma View Post
    If that were possible, what is that property returning when you call it?
    Hmm... Do you mean because you can never assign a value anymore? That makes sense lol. Perhaps like this
    vb.net Code:
    1. Public ReadOnly Property Value() As Integer = 15
    or using the constructor
    vb.net Code:
    1. Public ReadOnly Property Value() As Integer
    2.  
    3. Public Sub New()
    4.    Me.Value = 12
    5. End Sub
    This is perfectly valid for fields, so why not properties?
    Sure, you can never change it after that, and I can't really think of any use for that, but there are also ReadOnly fields that you can set like this, so why not?

    Well it does make sense I suppose. An automated ReadOnly property would have no advantage over a ReadOnly field, (except perhaps databinding? Not sure how much sense that makes for read only properties, haha).

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Default Property Values

    To answer the original question, setting field values where they're declared can be optimised by the compiler, so it's preferred over setting in the constructor, which can't be optimised.

    If you do choose to set in the constructor for some reason, and there could be valid reasons, then code duplication isn't an issue. You simply put the code in the default constructor and then invoke that from the others. If that's not possible for some reason, you simply create an Initialise method and set the field values there, calling that method from wherever it's appropriate.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  14. #14
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Default Property Values

    Quote Originally Posted by jmcilhinney View Post
    To answer the original question, setting field values where they're declared can be optimised by the compiler, so it's preferred over setting in the constructor, which can't be optimised.
    John, out of curiosity, what to your knowledge gets optimized by the compiler in the different scenarios?

    Given these 2 classes (both containing a value type and reference type), they produce identical IL ctors.

    Code:
    Public Class Class1
    
        Private _TestString As String = "HELLO WORLD"
        Private _Value As Integer = 10
    
        Public Sub New()
    
        End Sub
    
        Public Property TestString() As String
            Get
                Return _TestString
            End Get
            Set(ByVal value As String)
                _TestString = value
            End Set
        End Property
    
        Public Property Value() As Integer
            Get
                Return _Value
            End Get
            Set(ByVal value As Integer)
                _Value = value
            End Set
        End Property
    
    End Class
    
    Public Class Class2
    
        Private _TestString As String
        Private _Value As Integer
    
        Public Sub New()
            _TestString = "HELLO WORLD"
            _Value = 10
        End Sub
    
        Public Property TestString() As String
            Get
                Return _TestString
            End Get
            Set(ByVal value As String)
                _TestString = value
            End Set
        End Property
    
        Public Property Value() As Integer
            Get
                Return _Value
            End Get
            Set(ByVal value As Integer)
                _Value = value
            End Set
        End Property
    End Class

  15. #15
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Default Property Values

    Quote Originally Posted by kleinma View Post
    John, out of curiosity, what to your knowledge gets optimized by the compiler in the different scenarios?
    Hmmm... I don't actually know. I just read that somewhere reputable some time ago, but never investigated further.

    One point to consider with your testing: did you compile with optimisations enabled? Remember that optimisations are disabled by default for a Debug build.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  16. #16
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Default Property Values

    Yes they are still identical in a release build. It could be in certain very specific scenarios that certain optimizations are used when possible I suppose.

  17. #17
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Default Property Values

    Quote Originally Posted by kleinma View Post
    Yes they are still identical in a release build. It could be in certain very specific scenarios that certain optimizations are used when possible I suppose.
    Hmmm... or maybe the source wasn't as reputable as I thought. Can't recall where it was now as it was some time ago. Perhaps I've been deluding myself all this time. Maybe I'm not handsome and cool either!
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  18. #18
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Default Property Values

    lol.

    Well just so we can at least say one thing you SHOULDN'T do in terms of making it optimized, is to do something like this:

    Code:
        Private _TestString As String = ""
        Private _Value As Integer = 0
    
        Public Sub New()
            _TestString = "HELLO WORLD"
            _Value = 10
        End Sub
    which does effectively initialize the variables twice in the constructor.

  19. #19

    Thread Starter
    Lively Member
    Join Date
    Sep 2009
    Posts
    115

    Re: Default Property Values

    Thanks all for the responses. Exactly the information I was looking for.

    2 final parting questions.

    1) What could I have possibly done on my own to find this information for myself?

    2) It is safe to assume that values will be initialized in the declarations before the constructor is called?

    For example, if you have a field called "_FileName" with a default value set in the declarations, and a constructor with an optional "FileName" field where the user can optionally specify their own filename when creating a new instance of the class, it is safe to say that the default value in the declarations would not be able to overwrite the value set in the constructor.

    I think this is fairly obvious, but just to eliminate any doubt...

  20. #20
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Default Property Values

    Quote Originally Posted by wolfpackmars2 View Post
    1) What could I have possibly done on my own to find this information for myself?
    Searched MSDN and the web using appropriate keywords. The appropriate keywords may not be immediately apparent but, as you search and read, you can refine your search terms. Words like "constructor" and "initialize" would figure heavily.
    Quote Originally Posted by wolfpackmars2 View Post
    2) It is safe to assume that values will be initialized in the declarations before the constructor is called?
    Declarations MUST be processed before the constructor. If you initialise a field where it's declared then that assignment will also be performed before the constructor.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  21. #21
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Default Property Values

    1) MSDN documentation or a book on the language would provide information like this. (or ask on vbforums )

    2) in reality, no assignments can be made outside of a method/property. So when you declare a variable at the class level, and give it a value where you declare it, that value assignment is actually going to be done in the constructor when the code actually runs.

  22. #22
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Default Property Values

    Quote Originally Posted by kleinma View Post
    Yes they are still identical in a release build. It could be in certain very specific scenarios that certain optimizations are used when possible I suppose.
    You know, now that I think about it, maybe I was remembering incorrectly. I now have an inkling that the advice was to initialise a field in the constructor or on a declaration, which can both be optimised, rather than elsewhere, e.g. a Load event handler, which can't. I guess I'll never know for sure as I doubt I'd ever find the original source but I might investigate a bit to see what I can find on the subject.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  23. #23
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Default Property Values

    Quote Originally Posted by kleinma View Post
    2) in reality, no assignments can be made outside of a method/property. So when you declare a variable at the class level, and give it a value where you declare it, that value assignment is actually going to be done in the constructor when the code actually runs.
    That really is more correct than what I posted. I guess I was talking in a source code sense but, even then, I guess what I said is still not completely correct. For instance, placing breakpoints on lines 3, 5 & 6 of this code:
    vb.net Code:
    1. Public Class Class1
    2.  
    3.     Private number As Integer = 100
    4.  
    5.     Public Sub New()
    6.         Dim x As Integer = 200
    7.     End Sub
    8.  
    9. End Class
    reveals that line 5 is executed first, then line 3, then line 6. I guess the MSIL code would show exactly what happens. I really do need to make a point of disassembling more often, compared to my current which is pretty much not at all.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  24. #24

    Thread Starter
    Lively Member
    Join Date
    Sep 2009
    Posts
    115

    Re: [RESOLVED] Default Property Values

    Thanks all for your input on this question. I enjoy this forum and have learned a lot in the short time that I have been here and I definitely appreciate that I can post my questions here comfortably without being ridiculed for my simple questions.

    The only complaint I have is that some of the tougher questions I pose seem to go unresolved.

  25. #25
    Fanatic Member Megalith's Avatar
    Join Date
    Oct 2006
    Location
    Secret location in the UK
    Posts
    879

    Re: [RESOLVED] Default Property Values

    Quote Originally Posted by wolfpackmars2 View Post
    The only complaint I have is that some of the tougher questions I pose seem to go unresolved.
    I've found sometimes using another board will get a response on some subjects not answered on the vb.net forum, for example if i have a question relating to Httprequests then the ASP board gets better responses. Also showing some code in the opening post tends to help with replies.
    If debugging is the process of removing bugs, then programming must be the process of putting them in.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width