Search code examples
c#propertiesuser-controls

C# stop property change at runtime


I have been trying to build a user control with some custom properties set in the designer. However the control involves some interop code and settings which shouldn't be adjusted at runtime. Is there a way to stop the values being changed after they have been initially set by the designer code?


Solution

  • Are you able to modify the property definition? One approach is, add a sentinel to the property setter, and allow only one set operation (which would usually be done by InitializeComponent()):

    private int _myProperty;
    private bool _isMyPropertySet = false;
    public int MyProperty
    {
        set
        {
            if (!_isMyPropertySet)
            {
                _isMyPropertySet = true;
                _myProperty = value;
            }
            else
            {
                throw new NotSupportedException();
            }
        }
    }