About in parameter modifier on value type, properties and defensive copy

in parameter modifier was introduced in C# 7.2. It lets you pass (value) types by reference but at the same time protect you against modifying the actual instance.

Here is what What’s new in C# 7.2 says about it:

The in modifier on parameters, to specify that an argument is passed by reference but not modified by the called method.

Basically compiler protects you against modification of the instance in two ways:

  • when you try to change a field directly compiler will throw an error
  • when you call an instance method, compiler will create a defensive copy of the instance and run that method on the copy

But what happens when calling instance properties? Will compiler create a defensive copy as well? Even for autoimplemented getters? That’s the question I’ve got on my presentation and I wasn’t sure about it. On one hand properties in general can implement modification code and in that sense they aren’t safe just like methods aren’t. On the other hand autoimplemented getters don’t implement any modification code.

If I had to guess I’d say there is no need for defensive copies when dealing with autoimplemented getters, while in other cases compiler will resort to defensive copies.

After few experiments and using Reflector to inspect the generated code it turns out that compiler will use defensive copies with properties always, even with autoimplemented getters. You can also check it out with SharpLab.io, which is a great way into digging into (experimental) C#.

Looks like there is some room for improvement.

Leave a Reply