yusuf
yusuf

Reputation: 3646

About usage of DefaultValueAttribute Class in .Net

So here is the simple code:

    [System.ComponentModel.DefaultValue(true)]
    public bool AnyValue { get; set; }

I am sure I don't set AnyValue to false again (I just created it). This property is a property of a Page class of ASP.NET. And I am cheking the value in a button event handling function. But somehow it is still false. I wonder when actually it is set true? On compile time? When class is instantiated?

What do you think about what I am doing wrong?

Upvotes: 1

Views: 840

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062510

As already stated, it doesn't set values.

In addition to the PropertyGrid, [DefaultValue] is also used by various serializer implementations, such as XmlSerializer and DataContractSerializer. For info, there is also a second pattern: bool ShouldSerialize{Name}() that is respected by all 3.

Upvotes: 0

yusuf
yusuf

Reputation: 3646

So what is the best way to set default value like I meant?

This seems a good way for me;

    private bool myVal = true;
    public bool MyVal
    {
        get { return myVal; } 
        set { myVal = value; }
    }

Upvotes: 0

James Curran
James Curran

Reputation: 103485

DefaultValue does NOT set the value.

What it does is tell VisualStudio what the default value is. When a visual element (Button, listbox etc) is selected on a form, and the Property panel is displayed, VS will bold the values of properties which are set to something besides the value given in DefaultValue.

Hence in your case, since AnyValue is false, but it's DefaultValue is true, then is will display false in bold in the Property panel. If you were to manually change it to "true", then it will be displayed non-bolded.

Upvotes: 10

Related Questions