Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have both params and muti-object constructors?

Tags:

c#

constructor

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?

like image 705
Arithmomaniac Avatar asked Nov 24 '14 14:11

Arithmomaniac


1 Answers

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.

like image 111
Sean Avatar answered Nov 03 '22 01:11

Sean