I have a class in which a lot of properties. I need to dynamically change the attributes of some fields as soon as read. The fact is that the installation of this attribute depends on the input data. How to do it?

  • one
    You should not want to do this. You should revise the architecture of the application so that it does not require a dynamic change in access to the property. - Bulson
  • Bulson is absolutely right, imagine the problems of another programmer working with your classes, which change their behavior on the fly. - Alexander Muksimov
  • one
    Tell more precisely what you want to do for what . It depends on exactly how to do it. - VladD
  • @VladD, for example, I draw graphs, if there are no points on any graph, then I do not draw their graph at all. I have a main class, I open its copy through propertyGrid and there is some setting for the schedule that is missing. So what I wanted to do: if I don’t draw the schedule, I would like to hide the setting. - Naf
  • one
    You can hide the settings, no question. But for this, it makes sense to make the setting a Setting class, and simply assign the variable to null or new Setting() , depending on whether you need a setting or not. This design seems more appropriate to me. - VladD

1 answer 1

You can check in the setter whether it is possible to set the current property, and if not, then, for example, throw an exception:

 private int prop public int Prop { get { return prop;} set { if(canSetProp) prop = value; else throw new InvalidOperationException(); } } 
  • one
    In vain you suggest this. Dynamic change of access to a property is a deeply flawed practice, since entails difficult-to-fix architectural flaws. - Bulson
  • @Bulson, strictly speaking, there is no change in access to the property. In fact, in this case, the properties are used for their intended purpose: they allow you to add functionality before getting the value, or before setting the values. For simplicity, this can be considered the usual validation of input data. - Grundy
  • well, someone or something will have access to this canSetProp canSetProp and thereby become the implicit sovereign owner of access to this setter. Is not it so? - Bulson
  • one
    @Alexander Muksimov, in inept hands, anything will be a harmful invention. Puzzling Exception will not cause if the error text is clear. - Grundy
  • one
    Well, here we are called to chat and I think that we will not say anything new. I just think that children should be taught only good (including style) - they learn bad things themselves. - Alexander Muksimov