Every so often (e.g. NUnit's TestCaseData
), I see an object that has one or several constructors as follows:
MyObject(object arg)
MyObject(object arg1, object arg2)
MyObject(object arg1, object arg2, object arg3)
//guess they got tired of writing constructors?
MyObject(params object[] args)
If an object has the params constructor, though, what is the advantage of defining the previous ones?
It's typically for performance.
In your example it's probably the case that MyObject
is allocates with 1, 2 or 3 parameters, and therefore the developer has optimized for this. Firstly the underlying implementation may be optimized, and also at the call site the parameters can be passed without any additional memory allocation. By using a params
the compiler will have to insert code to create an array and then assign the parameters into that array before calling it. If it's the norm to call with 1, 2 or 3 parameters then you can avoid this allocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With