About using the DefaultValueAttribute class in .Net

So here's a simple code:

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

      

I'm pretty sure I haven't set AnyValue to false yet (I just created it). This property is a property of the ASP.NET page class. And I write the value to the button event handling function. But somehow this is still false. I wonder when this is actually true? At compile time? When is the class instantiated?

What do you think about what I am doing wrong?

+1


source to share


3 answers


DefaultValue makes NOT a value.

What it does is tell VisualStudio what the default is. When a visual (Button, listbox, etc.) is selected on the form and the properties panel is displayed, VS will be bold property values ​​that are set to something other than the value specified in DefaultValue.



Hence, in your case, since AnyValue is false but DefaultValue is true, then the property pane will display false in bold. If you have to manually change it to "true" then it will be displayed as non-bold.

+10


source


So what is the best way to set the default as I mean?

This seems like a good way to me;



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

      

0


source


As said, it doesn't set a value.

In addition to PropertyGrid

, it is [DefaultValue]

also used by various serializer implementations such as XmlSerializer

and DataContractSerializer

. For information, there is also a second template: bool ShouldSerialize{Name}()

which is followed by all 3.

0


source







All Articles