COMMUNITY

Optional parameters in constructor for C# target doesn't work with reflection

haxe-cs
(Peter ) #1

I’ve spotted that in Haxe C# target I cannot have optional parameters in constructor if I want to instance that class with reflection. I always need to send all the parameters to the Type.createInstance method otherwise I get “HaxeException: Invalid calling parameters for method .ctor” all the time.

Is this something that is going to be resolved or do I need to think about going around it in my codebase.

Thanks.

0 Likes

(Simon Krajewski) #2

The documentation on createInstance has a lot of fine-print:

Default values of constructors arguments are not guaranteed to be taken into account.
If cl or args are null, or if the number of elements in args does not match the expected number of constructor arguments, or if any argument has an invalid type, or if cl has no own constructor, the result is unspecified.

I think your case is supposed to fall under the first clause with the default value being an implicit null. We should clarify that though.

0 Likes

(Peter ) #3

Damn, thank Simon,

I was just being complacent that it works on Flash and JS target without a hitch. I was not really worried about the actual values of the parameters because I always use just uninitialized values null,0,"" etc. for them anyway. What got me was that now to successfully instantiate it I need to be aware of the number of arguments and their types at reflection time which I don’t.

0 Likes

(Simon Krajewski) #4

Well, it’s quite tricky on targets that support overloaded constructors. Reflection has some trouble figuring out what exactly you want to call here, because there isn’t just one clear answer like there is on other targets.

0 Likes

(Peter ) #5

Yep indeed, I will need to just go around it with other type of dependency injection instead of using constructor. This will however affect implementation in all existing targets as well which I was trying to avoid. Well, one can’t have everything, thanks. :slight_smile:

0 Likes