Function parameters tend to have different purposes : in most case they are just readonly indications used by the internal logic to produce a result/effect, but sometimes they are modified by the calling function (initialisation function, sorting algorithm etc).
I was wondering if there is a best practice to show in the code that the function is going to modify a parameter (apart from writing a comment above stating this explicitly)? Like a widely recognized coding convention.
With C++ I use the ‘const’ keyword for every parameter which is not going to be modified by the function, but C# does not allow const or ‘readonly’ to be used that way. And a lack of ‘const’ does not really mean that the parameter is intended to be updated by the function anyway.
Thanks
Actually in C# valued-type parameters (and strings, due to immutability) are “const” by default, unless you explicitly mark them with
outorrefkeywords. As for reference types function can only modify object that the parameter refers to, not the reference itself.Moreover, those
outandrefkeywords are hints for compiler, that analyzes the flow of code and dissallows use of “uninitlized” variables. So. i.e. if you declare method:and then try calling it from the following code:
the compiler will disallow, as
xwill be uninitialized at the time of call. On the other hand:the following call is now allowed:
as compiler now knows that
DoSomethingis going to initialize x. Notice, thatDoSomethingwon’t compile unless it containts a statament, that assigns some value toiparameter.