void IncrementAndPrint(in int Counter) { Counter++; // this will throw error. Console.WriteLine(Counter); } void Print(in int Counter) { Console.WriteLine(Counter); }
We could delve into details of “in” on a later post, however, for this post, we will focus on the readability factor. One of the features of “in”, which separates it out from “ref” and “out” is that, you don’t necessarily (yeah…keyword is optional during invocation) use the keyword before using it. For example, for the above method Print , both following method invocation is valid.
int counterValue = 3; Print(in counterValue); Print(counterValue);
However, the framework restricts you from passing an expression or direct value with the “in” parameter. This restriction is not valid if you are not using the optional “in” keyword.
Print(in 3); // Invalid code Print(3); // This is valid.
Another scenario worth consideration is when there is an overloaded method of Print which doesn’t use the pass by reference. Consider the following two overloaded methods.
void Print(in int Counter) { Console.WriteLine($"Pass By Reference :{Counter}"); } void Print(int Counter) { Console.WriteLine($"Pass By Value :{Counter}"); }
Understandably, the first method uses “in” keyword to pass the parameter by reference, while the second passes the parameter by value. Considering the “in” parameter is optional, what would be the output of following method invocations.
int num = 3; Print(in num); Print(num);
Output
Pass By Reference : 3 Pass By Value : 3
It is on expected lines as Microsoft would have wanted, however, the question is, does the ability of “optional in” do justice to readability of code ?