Why Would One Ever Use the "In" Parameter Modifier in C#

What is the point of the in modifier for classes

in is compiled to IL in exactly the same way as ref, except in argument is marked with IsReadOnly attribute.

That means in behaves exactly as ref, but compiler (not runtime) enforces that you don't assign value to in argument.

So, as you correctly pointed out - in referenece-type argument is passed by reference (which means reference is not copied and points to original location), but compiler prevents you from changing it. I don't really see much use for it for reference types, but it won't hurt to have that, at least for consistency.

Should I always use the 'in' parameter modifier when possible?

You should definitively get a close look to the documentation and use the in modifier for specific use case that you can find into your code path / profiling / optimization.

Remember that, 'best performance' is usually meaningless out of it's context. :)

Is it useful to put the C# 7.2 'in' parameter modifier everywhere

No, it's not useful to (blindly) put the in parameter modifier everywhere, because the compiler might create defensive copies.

A concrete example can be found in the following question:

  • Using C# 7.2 in modifier for parameters with primitive types

Why can you still modify a List when it has the in parameter modifier in C# 7.2

The in modifier only restricts assigning to the reference, but the List<T> is still accessible and mutable. Basically it works like ref readonly.

You can't do myList = new List<int>.

Is the in parameter modifier really optional on the call site?

I think you are misunderstanding the article.

The way I understand it is that considering the following method:

void Foo(in SomeBigValueType t)
{ ... }

The following two calls are the same:

SomeBigValueType v;
Foo(v);
Foo(in v);

Your issue seems to be unrelated to the article. in needs a storage location (aka variable). In your second example you aren’t passing one so you get an error; you’d get the same error with ref or out.

Purpose of in parameters in C#

"in" Can be used to pass a variable as a read-only reference (value type and reference type both).
Reason to pass read-only reference is that, if I pass a value type variable without reference, then each time a new copy will be created. So, it will take extra memory and performance will be slower.



Related Topics



Leave a reply



Submit