Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using methods as a default parameter

Tags:

c#

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.

like image 548
TankorSmash Avatar asked Dec 04 '25 17:12

TankorSmash


1 Answers

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");
    }
like image 53
P.Brian.Mackey Avatar answered Dec 06 '25 12:12

P.Brian.Mackey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!