Suppose I have an object:
public class A
{
private int m_a;
private int m_b;
A(int a, int b)
{
m_a = a;
m_b = b;
}
}
This gets the job done but I have a hazy memory of being told it unnecessarily copies the integers into arguments a and b and then into m_a and m_b. Is there a way to define the class such that the parameters pass straight through to their member counterparts?
Please note that I don't want to discuss C# Object Constructor - shorthand property syntax as here the onus is upon the person using the class.
Of course I could be entirely wrong and maybe the compiler removes such trivialities thus I should be happy to be educated either way.
This works but I have a hazy memory of being told it unnecessarily copies the integers into arguments a and b and then into m_a and m_b.
Yes, the values are copied into the parameters a
and b
, and then into the state of the object itself.
Fundamentally that's just part of how member invocations work, and is unavoidable. A future version of C# may well have a way to make that simpler to express in source code, but the "overhead" which is present will still be present - and is utterly insignificant in the vast, vast majority of programs. (It may be optimized away by the JIT compiler by inlining, in fact... but you should almost certainly not worry about it.)
See more on this question at Stackoverflow