1

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?

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

That's fine. Or set it in the constructor.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.