I have a method that accepts a few arguments:
public Something GetMeSomething(Class1 class1, Class2 class2, Class3 class3, bool someOption);
I don't like the fact that it accepts so many arguments, with some bool
at the end, which also doesn't look great. Int the context of this method these arguments are related to each other, and they could be a part of a single object.
However, I do not want to create a new class like this:
record SomeArguments(
Class1 Class1,
Class2 Class2,
Class3 Class3,
bool SomeOption
);
because it incurs allocations.
However, I thought about making it a struct:
record struct SomeArguments(
Class1 Class1,
Class2 Class2,
Class3 Class3,
bool SomeOption
);
I know that it's not advised to use struct when the content of it is bigger than 16 bytes. I assume that this struct will be bigger than that, it would probably store pointers to instances of the classes inside.
What would you do?
not advised to use struct when the content of it is bigger than 16 bytes
This rule really needs a disclaimer. You should certainly try to keep structs small, but there is no real limit. It really depends on how it is used.
In your specific example you are copying the same amount of data if you call GetMeSomething
with separate parameters, or with all parameters in a struct. So I would not expect a significant difference.
You can often also avoid the copy overhead by passing structs with the in parameter modifier.
I assume that this struct will be bigger than that
Yes, if running in 64 bit mode each reference will use 8 bytes, so probably 52 bytes. Use Marshal.SizeOf to check. Keep in mind that the System.Numerics.Matrix4x4 is 64 bytes, so such a size is not necessarily a concern.
If you are concerned about allocations or performance, the most important part is to measure. Run a profiler and see if you can see any difference. Chances are that there is an irrelevant or immeasurable difference. Most code run rarely enough that performance concerns are nearly irrelevant. It is better to profile the code and spend the effort at optimizing the places that actually matter.
As for if it is a good idea to wrap parameters in a struct, it really comes down to readability. If you think it makes the code clearer and more readable, go for it.