I was looking at a piece of error handling code that looks like this:
if (condition) {
thereIsAProblem = true;
problemDescription = "x";
}
if (!thereIsAProblem && condition2) {
thereIsAProblem = true;
problemDescription = "y";
}
And I got to wondering whether there is a way to define a local variable called thereIsNotAProblem
that is dynamically based on the value of thereIsAProblem
. In other words:
var thereIsAProblem = false;
var thereIsNotAProblem = *** some expression... ***
Console.WriteLine(thereIsNotAProblem); // true
thereIsAProblem = true;
Console.WriteLine(thereIsNotAProblem); // false
if (thereIsNotAProblem && condition3) {
..
}
Is there some expression that can be entered on the line above that would assign the value of thereIsNotAProblem
to be a dynamic formula based on !thereIsAProblem
, and still allow thereIsNotAProblem
to be supplied anywhere a bool
value is required?
Not quite... but you could make it a delegate instead:
Func<bool> thereIsNotAProblem = () => { /* some expression */ };
Console.WriteLine(thereIsNotAProblem()); // true
thereIsAProblem = true;
Console.WriteLine(thereIsNotAProblem()); // false
Note how now each time was want to evaluate thereIsNotAProblem
we invoke the delegate... which evaluates the expression to get a bool
value.
See more on this question at Stackoverflow