Results 1 to 2 of 2

Thread: DefaultValue Attribute

  1. #1

    Thread Starter
    Hyperactive Member Krokonoster's Avatar
    Join Date
    Jan 2010
    Location
    Cape Town
    Posts
    448

    DefaultValue Attribute

    Thought I found a very usefull attribute this morning that would eliminate the need to set class member defaults in the constructor, nl. the DefaultValueAttribute Class

    However when using it I found that my booleans still are set to "false" when I create a class instance, even though I decorated the member with a # [DefaultValue(true)]

    Someone pointed out the following in the documentation, which explains that:
    A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
    Don't make sense...what is the use of this attribute then?


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

    Re: DefaultValue Attribute

    Makes perfect sense. What namespace is the DefaultvalueAttribute a member of? System.ComponentModel. What is the purpose of that namespace? To control designer behaviour. The documentation also says this:
    You can create a DefaultValueAttribute with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member.
    What you're talking about is the initial value, not the default value. Basically, the default value is what the property gets set to when you right-click it in the Properties window of the designer and select Reset.

    Also, if you want an initial value for a property that is different to the default value for its type, you don't have to set them in the constructor. You can declare a backing field explicitly and initialise that where it's declared. This is actually better because the compiler can optimise such code better.
    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

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