I have an existing method like below: the method body has over 1000 lines of code that I can't bring it here, just in method body if the value of argument (I mean index_param) be changed then surly I get wrong results.
public String calculateValue(int index_param) {
//a highly complicated transactional method which returns a String
}
I want to be sure the method body is not changing index_param during operation, and prevent it from changing the parameter. what do you prefer for this scenario?
Unfortunately, C# doesn't have a local variable analogue of readonly.
You could use a Code Contract Assert Requires pseudo post-condition for this, although I can't see a way to avoid an additional local variable which could also, in theory, be mutated.
public String calculateValue(int index_param) {
int __DO_NOT_MUTATE_ME = index_param;
// a highly complicated transactional method which returns a String
//
Contract.Assert(index_param == __DO_NOT_MUTATE_ME, "No! Don't change the local var");
return result;
}
Edit - Some findings
Code Contracts aren't as suited toward detecting stack variable mutation as expected.
Contract.Ensures() must be at the top of the code block, and Ensures is only designed to reason over return values, not local vars.Contract.Assert is thus cleaner as it can be placed anywhere in the block. It throws if the stack variable is mutated at run time.index_param (marked with Red Arrow), it instead flags a warning with our contract as the nonsensical "Consider adding Contract.Requires(index_param + 1 == index_param);". Hmmm ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With