Declaring methods with `in` parameters

If a I'm writing a synchronous method, should I always declare read-only value types with the in keyword.
void Foo(in int i)
{

}
void Foo(in int i)
{

}
9 Replies
Angius
Angius2w ago
in is basically readonly ref Only matters when passing some super large structs, to avoid copying fwiw, I've seen in used in the wild maybe, like, twice
nathanAjacobs
nathanAjacobsOP2w ago
But are there downsides to declaring it like this or is just overkill? From what I understand the caller doesn't have to specify the in keyword when calling the method, but still benefit from it.
Angius
Angius2w ago
Overkill And only really works with value types For reference types, you're already passing a reference
nathanAjacobs
nathanAjacobsOP2w ago
Yeah I know it is just for value types, but was just curious what the general consensus was. Like at what point do I need to consider using it
333fred
333fred2w ago
There are downsides, yes. There's more overhead to ref parameters Unless you have a struct over 16 bytes, you probably shouldn't use it
nathanAjacobs
nathanAjacobsOP2w ago
Okay now I'm curious, what is the overhead?
333fred
333fred2w ago
Refs are tracked by the gc
nathanAjacobs
nathanAjacobsOP2w ago
even for structs that contain no reference types?
333fred
333fred2w ago
Yes. The location of the struct could change For example, if you passed a ref to a field of a reference type Even if there's no chance the location can change, knowing that is a tiny bit of overhead

Did you find this page helpful?