C# in parameter modifier

In version 7.2 of C# language, now we can pass an argument into a method without allowing the method to mutate the value. But the main reason this keyword is added to the language is not mutability. It was added for optimization and the need to pass a value type in a method by reference while avoiding the cost of copying the value every time the method is called. In this post we’re going to see how this keyword is used. Then I’m going to bring up some reasons why there might be a better alternative to solve this kind of problems.

How to use C# in parameter modifier

We already have the ref and out parameter modifier keyword in C#. They help us to pass value types by reference into a method. By using these modifiers we are able to mutate the value of our value type parameter. Sometime this is what we actually intend. But sometime this is also used to optimize how the values are passed into the method. Because we don’t want to copy the entire value every time we call the method. But we also might want our value to be immutable, but we can’t achieve this with ref and out keywords.

With C# in parameter modifier we can achieve this, here an example from MSDN.

As you can see we only use this keyword in method definition and not at the call site.

Other Alternatives to in parameter modifier

I think it’s worth to mention that in parameter modifier should be used when we want to pass something by reference for optimization purposes. But we don’t actually want to mutate the value, so in allows us to pass the value by reference safely without allowing the method to mutate our value.

In my opinion we should use this method only when we are stuck with a primitive types. Also when we can’t do anything about it. Otherwise I think it’s better to create a class that has a property that is readonly and pass that class to the method instead, something like.

By doing this when we use this object we achieved both passing something by reference so not making expansive copies. Also the value is not mutable so we can be sure that our value is still valid. I think it’s also easier to reason about the validity of our immutable object. That is we are the one who control our object and how it’s used and not the user of our class or data.

Summary

In this post we saw what the C# in parameter modifier was and how to use it. We discussed some ideas about when and how to best use it. We also saw what better alternative exists to help us to achieve the same result.

Share...
 

Hamid Mosalla

Hi, I'm Hamid Mosalla, I'm a software developer, indie cinema fan and a classical music aficionado. Here I write about my experiences mostly related to web development and .Net.

 

Leave a Reply

Your email address will not be published. Required fields are marked *