I'm doing C# (with Unity3D / Mono Runtime 2.6.5) quite for a while now, but recently I encountered a very strange behaviour, when calling an event where a method with a boolean default parameter is attached to.
When attaching it directly (Case 1), it somehow becomes true
, even though the default value is false
. While when attaching it via a lambda expression (Case 2), it is correctly set to false
.
I really had expected it to become false
in any case, where the param is not provided.
Attached you can find an example code of this strange behaviour:
public class SomeClass
{
public event Action SomeEvent;
public void TriggerSomeEvent()
{
if (SomeEvent != null)
{
SomeEvent();
}
}
}
public class AnotherClass
{
public AnotherClass(SomeClass someClass)
{
someClass.SomeEvent += AnotherMethod; // Case 1: somehow "someParam" becomes true
someClass.SomeEvent += () => AnotherMethod(); // Case 2: "someParam" becomes the expected false
}
void AnotherMethod(bool someParam = false)
{
// How can "someParam" in the first case (see above) become true?
Debug.Log(someParam);
}
}
Invoke the example by:
void OnGUI()
{
if(GUILayout.Button("test"))
{
var someClass = new SomeClass();
var anotherClass = new AnotherClass(someClass);
someClass.TriggerSomeEvent();
}
}
Output:
true
false
Update
Like Iain Smith pointed out the output is more of a random nature. So the first output does not always become true
, it also turns to false
from time to time.