Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: best way to make an argument of a method unchangeable

Tags:

c#

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?

like image 644
nil Avatar asked Dec 05 '25 13:12

nil


1 Answers

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.
  • If static analysis is enabled, there is SOME (post) compile time benefit as well, as per the attached images (Top shows the warnings with the bad code, bottom shows no warnings with no mutation). However, instead of flagging the bad line of code which mutates the 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 ...
  • You can download the Code Contracts plugin for Visual Studio here - an additional tab is added to the Properties dialog.

enter image description here

like image 85
StuartLC Avatar answered Dec 07 '25 04:12

StuartLC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!