Action as a optional parameter in a function

11,976

Solution 1

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"); }

    ...
}

Solution 2

One workaround for this may be to just use classical overloading:

public void DrawWindow(Rect p_PositionAndSize, string p_Button2Text = "NotInUse")
{
    DrawWindow(p_PositionAndSize, delegate{ Thread.Sleep(1); }, p_Button2Text);
}

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

This way you can specify the default action in the overload with two parameters.

Share:
11,976
Esa
Author by

Esa

Updated on June 25, 2022

Comments

  • Esa
    Esa almost 2 years

    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?

  • nemesv
    nemesv almost 11 years
    But OP wants to have a default action there like delegate{ Debug.Log("NotInUse"); } and not null
  • vendettamit
    vendettamit almost 11 years
    Then I think you should go with the Mario's suggestion. As per the language spec you can not use default value apart from null to reference types. only strings are allowed to have values in default parameters.
  • RustemMazitov
    RustemMazitov about 7 years
    if you want null as default action you can use: p_Button2Action?.Invoke();
  • Matthew Watson
    Matthew Watson about 7 years
    @RMazitov Note that the null coalescing operator is only available in C# 6 or later - so it's correct to use that now (but obviously it didn't exist in 2013)
  • RustemMazitov
    RustemMazitov about 7 years
    yes, good point. thanks for bringing that up)