Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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; }
    }

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top