As of C# 7.2+, you can add a parameter modifier in
before the parameter type to define a parameter as const, essentially.
It is like the ref or out keywords, except that in arguments cannot be modified by the called method. - MSDN
Example from MSDN:
void InArgExample(in int number)
{
number = 19; // error CS8331, it prevents modification of this parameter
}
Why is it useful? You can guarantee the caller that the argument passed will be unmodified as a result of calling that function. A promise in other words.
According to SOLID design principles and Clean Code by Robert Martin, is this considered a code smell along the same lines as out
parameters?
Sources:
in
parameter is passed by reference. Usually C# prevents the modification of parameters passed into the method by making a copy, which is the default. Thus, the purpose ofin
is not to prevent the modification of parameters. If you want to allow the modification of the parameters, you opt out withref
(do not confuse with reference types). The purpose ofin
is to avoid the copy. Since no copy is done when usingin
, the constraint of not modifying the parameter has to be enforced by your code, the compiler checks that. Again, if you want to modify it, useref
.out
is also a parameter passed by reference. And also allows the modification just likeref
. Except it guarantees that the value will be initialized by the method, and the compiler checks that.