TankorSmash
TankorSmash

Reputation: 12747

Using methods as a default parameter

I'm looking to create a Button class in my custom XNA GUI that accepts methods as an argument, similar to how, in Python's tkinter you can just set the function to be called with Button.config(command = a_method) .

I've read about using delegates as parameters here, here and here, but I don't seem to be any closer to getting it working. I don't fully understand how delegates work, but I've tried several different things unsuccessfully, like using Func<int>? command = null in order to test later to see if command is null then I'd call the preset default, but then I get a Func cannot be nullable type or something similar.

Ideally the code'd be something like:

class Button
{
//Don't know what to put instead of Func
Func command;

// accepts an argument that will be stored for an OnClick event
public Button(Action command = DefaultMethod)
  {
    if (command != DefaultMethod)
    {
       this.command = command;
    }
  }
}

But it seems like everything I've tried is not working out.

Upvotes: 3

Views: 248

Answers (3)

P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

Default parameters must be a compile time constant. In C#, Delegates can't be constants. You can achieve a similar result by providing your own default in the implementation. (just using Winforms here)

    private void button1_Click(object sender, EventArgs e)
    {
        Button(new Action(Print));
        Button();
    }

    public void Button(Action command = null)
    {
        if (command == null)
        {
            command = DefaultMethod;
        }
        command.Invoke();
    }

    private void DefaultMethod()
    {
        MessageBox.Show("default");
    }

    private void Print()
    {
        MessageBox.Show("printed");
    }

Upvotes: 1

Oded
Oded

Reputation: 499002

The error you got about Func<T> not being nullable it right - it is a reference type and only value types can be nullable.

To default a Func<T> parameter to null, you can simply write:

Func<int> command = null

Upvotes: 0

user153923
user153923

Reputation:

If you are interested in a default value, would something like this work?

class Button
{
  //Don't know what to put instead of Func
  private readonly Func defaultMethod = ""?
  Func command;

  // accepts an argument that will be stored for an OnClick event
  public Button(Action command)
  {
    if (command != defaultMethod)
    {
       this.command = command;
    }
  }
}

Upvotes: 0

Related Questions