mardi 17 juillet 2018

Conditional Variable Scope in C#

So this is kind of an odd question, is there any way to modify a variable's visibility depending on a certain condition (e.g. via some attribute)?

This may be more of a design pattern question, so allow me to explain my situation:

I have a class which has many user configurable values (9 total, 4 of which are conditional). However, some of these variables only apply if certain conditions are met. Right now, they are all visible to the user. I'm looking for a way I can restrict the visibility of certain variables at compile time in a per-scope context. I want to avoid getting the user confused and having them potentially set certain values that will just get ignored.

Example:

Property B only applies if property A is true. If the user sets A to false, the current scope will lose visibility of B.

var settings = new Settings() {
    A = true,
    B = ... //Everything is fine since A is true
}


var settings = new Settings() {
    A = false,
    B = ... //Compile Error, Settings does not contain definition for "B"
}

//Somewhere that uses the settings variable...
if(A) { useB(B); } else { useDefault(); }

Is there a better solution to this than "good documentation?"

Aucun commentaire:

Enregistrer un commentaire