Search code examples
c#attributescontrol-library

C# DefaultValue attribute not working


I'm using C# windows forms control library program to create my own control, the code as follow:

    public partial class MyControl : UserControl
    {
        public MyControl()
        {
            InitializeComponent();
        }

        private float mMinValue;

        [Browsable(true)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        [Category("Design") , DefaultValue(0.0)]
        public float MinValue
        {
            get { return mMinValue; }
            set { mMinValue = value; }
        }

        private float mMaxValue;

        [Browsable(true)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        [Category("Design") , DefaultValue(1.0)]
        public float MaxValue
        {
            get { return mMaxValue; }
            set { mMaxValue = value; }
        }
    }

When the program runs, the default value of MinValue and MaxValue are both 0, so how to set the default value correctly?


Solution

  • The Default value attribute only indicates the designer what is the default value of the propery. It does not set it as the actual value of the member behind the property. This is also mentioned on the MSDN page for the default value attribute:
    (in the remarks section)

    Note
    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.

    So, as others have already mentioned, you need to set these values in the code yourself (I like to do it in the constructor and not in the declaration of the private members, but I think it's just a matter of personal preference).