Function overloading with and optional arguments
Hi folk. I need your help. Can you explain script behaviour?
There is a test project with one button and one script.
script:
using UnityEngine;
using System;
public class TestScript : MonoBehaviour {
private void TestFunc(object value, Action action = null) {
Debug.Log("Single");
}
private void TestFunc(object[] value, Action action = null) {
Debug.Log("Array");
}
public void OnClick() {
object single = new object();
this.TestFunc(single); // <-- All good
object[] array = new object[] { };
this.TestFunc(array); // <-- Error is here
}
}
MS VS 2016 doesn't show any errors.
But I received error in Unity:
Assets/TestScript.cs(18,10): error CS0121: The call is ambiguous between the following methods or properties: 'TestScript.TestFunc(object, System.Action)' and 'TestScript.TestFunc(object[], System.Action)'
PS: sorry for my English
PPS: this is compiler bug
I'm glad to inform that we have fixed this and will be released with the new version of our compiler (on Unity 5.5)
Answer by btmedia14 · Jun 17, 2016 at 05:41 PM
The first function with the single Object signature
private void TestFunc(object value, Action action = null)
allows the function to to be called with any object as the first parameter. Object is the base class for everything in Unity. As such it will accept arrays of objects or any other datatypes derived from Object. An array of Objects is just another Object. However, in the case of Object[] as a parameter, the compiler also happens to pattern match against the second method signature. Hence the ambiguity. If the datatypes were other than Object, say int, the method signatures would be considered unique enough when being called with an array of ints.
But why in case of
private void TestFunc(object value)
and
private void TestFunc(object[] value)
There are no errors?
That is interesting. There should be compile time errors in both sets of signatures. I checked under Visual Studio 2015 as well as $$anonymous$$onoDevelop and do see compiler errors of the type you listed earlier in both cases. For Visual Studio ensure the error filter within the Error List window is not suppressed else no errors will be listed even though errors are generated.
Here is screen with both situations. And i have only one error message only in unity. Interesting! If I reload Unity, without change any code in VS, I have NO errors in Unity and I can run project. But executed only "single" version of "TestFunc_1" If I change any code in VS, i receive same Unity error.
And here is VS-only console project. Everything is O$$anonymous$$!