Reference Semantics and Code Readability

One of the features Microsoft packed with C# 7.2 is Reference Semantics with Value Types. Though designed with the intention to improve performance by eliminating the need for copying (and thereby allocating memory) value types , I do have my reservations on the complexity it adds to readability of code for a programmer. Let’s consider the case of “in” keyword.

 

The “in” allows the programmer to pass a parameter by reference, but on the condition that the method cannot modifying the value.  For example
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 ?

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s