- Home /
Method overloading fails with implicit typecasting and optional parameters
Hi,
I posted an "opening" to this question earlier and thanks to tswalk I realized one very huge weirdness, related to Unity and method overloading.
I encountered an issue while creating method overloads. This compiles without problems (EXAMPLE A):
void Test(Color v, bool b)
{
Debug.Log("color");
}
void Test(Vector4 v, bool b)
{
Debug.Log("vector4");
}
void Start()
{
Test(Color.red, true);
}
While this generates an ambiguous call error (EXAMPLE B) (same as above, but the Test methods have optional parameters):
void Test(Color v, bool b = true)
{
Debug.Log("color");
}
void Test(Vector4 v, bool b = true)
{
Debug.Log("vector4");
}
void Start()
{
Test(Color.red);
}
This is apparently due to the fact that Vector4 and Color can be implicitly cast to each other (and are part of the UnityEngine DLLs), and the compiler, in case there are added optional parameters, goes crazy. The issue is purely Unity-related (a Unity Assembly generated in Visual Studio doesn't generate any ambiguity, even if it contains calls to methods with implicitly castable types and optional parameters).
In short, the overloads and relative call in EXAMPLE B should totally work, while instead they don't.
Can anyone share some light on this? Or it's just a known bug?
EDIT
Just out of curiosity, tswalk notes that calling Test and including the optional parameter like this:
Test(Color.red, true);
works both with EXAMPLE A and B
what does this script do and what is Test(col); calling
The script doesn't do anything: it's just for testing purposes in order to replicate the issue. Copy/pasting it inside a $$anonymous$$onoBehaviour will generate the ambiguity error. "col" is just a Color, but I now replaced it with Color.red so it's more clear
so your having copy and pasting problems with monoBehaviour? $$anonymous$$y friend has problems with that and if thats what the problem is you have to reinstall windows usually. but theres a lot to try befor that.
Uh no, it's not a copy/paste error :P I meant that you can copy/paste that same code and see that it generates an error, while ins$$anonymous$$d it should not (because the overloads in EXA$$anonymous$$PLE B should totally work).
had to do some research on the optional parameters and it seems C# 4.0 has spoiled us a bit there... since Unity/$$anonymous$$ono is stuck at 2.0 compatibility with its' own apparent variant on 3.0/.5, seems that optional parameters don't work.
[edit] also, using your example.. if you force the "optional" parameter in calling, the ambiguity goes away... and the overloaded method signature is recognized properly.
Your answer
