Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using in modifier in C#

It is known that in C# you can pass a value type to a method by reference with the ref modifier.

struct Point {
 float x, y
}

float Dst(ref Point a, ref Point b) {
 //code
}

In this case, when calling a method, you must also specify ref opposite the corresponding parameter.

Point a, b;

//point initialization

float dst = Dst(ref a, ref b);

There is also the in modifier, which works much the same as readonly ref, but it does not have to be specified when calling the method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

float Dst(in Point a, in Point b) {
 //code
}

.

Point a, b;

//point initialization

//both variants are possible
float dst = Dst(in a, in b);
float dst = Dst(a, b);

What’s the difference between specifying the in modifier when calling a method and not specifying it? Does the structure get copied in one case or another?

P.S. I know about the readonly ref in new versions of C#, but I use older version.

>Solution :

What’s the difference between specifying the in modifier when calling a method and not specifying it? Does the structure get copied in one case or another?

When you use in, you still end up passing by reference (like with ref) so the value itself is not copied – but the intention is that because the method "can’t" change the value, you won’t end up being able to tell the difference. That’s why you don’t have to specify it at the call site.

There are ways of getting around this – but they usually involve being sneaky just to prove that you’re breaking things.

In terms of the difference between in and readonly ref, the feature specification is probably the best source of information.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading