Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action as a optional parameter in a function [duplicate]

Is it possible to have an Action as an optional parameter in a function? The button2Action should be optional.

public void DrawWindow(Rect p_PositionAndSize, string p_Button2Text = "NotInUse", Action p_Button2Action)
{
 // Stuff happens here
}

I tried it with e.g p_Button2Action = delegate{ Debug.Log("NotInUse"); } but it does not compile due to Default parameter value for p_Button2Action must be a compile-time constant. How do you make an optional Action that is a compile time constant?

like image 602
Esa Avatar asked Jun 27 '13 07:06

Esa


1 Answers

You must specify a constant value for a default parameter, so the only default value you can specify for an Action is null.

However, it's easy to check for null and substitute the correct value:

public void DrawWindow(Rect p_PositionAndSize, string p_Button2Text = "NotInUse", Action p_Button2Action = null)
{
    if (p_Button2Action == null)
        p_Button2Action = delegate{ Debug.Log("NotInUse"); }

    ...
}
like image 141
Matthew Watson Avatar answered Oct 04 '22 03:10

Matthew Watson