Reputation: 105
I am just curious, is there any advantage of using the in
keyword for a reference type parameter (like string
)?
Sample:
bool IsNice(string greeding)
{
return greeding.Contains(":-)");
}
VS
bool IsNice2(in string greeding)
{
return greeding.Contains(":-)");
}
Upvotes: 4
Views: 664
Reputation: 203844
The two behave differently.
In the second example any changes made to the variable you pass by reference will be observed by the method.
In the first case you're not passing in a variable, you're just passing in a value. If you got that value by getting the value of a variable, then any changes to that variable afterwards won't be observed.
It's going to be rather difficult for the variable to change after the initial call to the method, so I wouldn't expect it to matter in practice very often, but it's possible.
Upvotes: 0
Reputation: 42320
In performance terms, probably not much. You're adding an extra dereference.
Take the code
public class C
{
public void WithoutIn(string s)
{
Console.WriteLine(s);
}
public void WithIn(in string s)
{
Console.WriteLine(s);
}
}
This gets jitted as:
C.WithoutIn(System.String)
L0000: mov ecx, edx
L0002: call System.Console.WriteLine(System.String)
L0007: ret
C.WithIn(System.String ByRef)
L0000: mov ecx, [edx]
L0002: call System.Console.WriteLine(System.String)
L0007: ret
(SharpLab).
The only difference is mov ecx, [edx]
rather than mov ecx edx
. I would imagine this dereference would slow things down slightly, but not by any observable amount.
In practical terms, it means you cannot do this:
public void M(in string s)
{
s = "foo"; // CS8331: Cannot assign to variable 'in string' because it is a readonly variable
}
in
was added to the language to enhance support for passing structs by reference. I'd call into question any code which used it with a reference type: I'd assume that it came about as the result of a value type being later changed into a reference type, and not because of some deliberate decision.
Upvotes: 3
Reputation: 760
From "In Parameters in C# 7.2 – Read-only References":
In parameters in C# are like ref parameter only, except they are read-only inside the method. And, they can’t be modified further. You can only refer them.
So read only?
Upvotes: 2