MiguelPT
MiguelPT

Reputation: 29

Call method without parameters

I have a quick C# question.

I have a list that I need to pass onto a method. So I did this:

Form2 f2 = new Form2(JogadoresList);
f2.novoJogo(JogadoresList);

And on another class:

public void novoJogo(List<Jogadores> JogadoresList)
    {}

But now I want to call the novoJogo method from a

private void button1_Click(object sender, EventArgs e)
    {
    }

method. How can I call the novoJogo method if I don't have parameters to pass onto it and don't want to replace the novoJogo's list? Thank you.

Upvotes: 0

Views: 6795

Answers (3)

Aly Elhaddad
Aly Elhaddad

Reputation: 1943

Change the access-level of JogadoresList to public static or internal static so you can access it via button1_click.

Upvotes: 0

BradleyDotNET
BradleyDotNET

Reputation: 61349

Either the method needs the list, or it doesn't. So the fact you are asking this is... troubling.

However, you have a couple options. Just pass null:

private void button1_Click(object sender, EventArgs e)
{
   //Hopefully you held onto that reference!
   f2.novoJogo(null);
}

Or use default arguments/optional parameters:

public void novoJogo(List<Jogadores> JogadoresList = null)
{}

private void button1_Click(object sender, EventArgs e)
{
   //Hopefully you held onto that reference!
   f2.novoJogo();
}

In both cases, make sure that novoJogo will be OK with a null list passed to it (NRE is really easy to get here if you weren't careful). And consider if your design makes sense here, if only part of the function needs the list, should that really have been two functions instead of one?

Upvotes: 1

ocuenca
ocuenca

Reputation: 39326

You can just call novoJogo passing null value as parameter:

novoJogo(null);

Or an empty list:

novoJogo(new List<Jogadores>());

Also in the novoJogo method, you could define the List<> as an optional parameter:

public void novoJogo(List<Jogadores> JogadoresList=null)
{}

Then, you can call it without passing the argument in the the click event as I show below:

private void button1_Click(object sender, EventArgs e)
{
   novoJogo();
}

Upvotes: 1

Related Questions