0

How do you declare a progress bar as an optional parameter?

Here is the function:

public int Factorial(int number, System.Windows.Forms.Label l, System.Windows.Forms.ProgressBar newprogressbar, int time=0)
    {

      ....

    }

The function has four parameters. Only int number and the label l should be mandatory. time is already optional, but I don't know how to make the new progressbar optional. The function returns the factorial of a number and it's uses a label to display it.

The progress bar should show the state of the stack and the time should be the speed at which the function works, but these two should be optional.

I have already done the function, but I still need to figure out how to make the progressbar optional.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
robertpas
  • 643
  • 5
  • 12
  • 25

2 Answers2

3

The same way you declare any other parameter to be optional - you specify a default value. However, the default value has to be a constant, which for reference types other than string basically means null:

public int Factorial(int number, Label l, ProgressBar newProgressBar = null,
                     int time = 0) {

Personally I would change the design, however. Instead of making Factorial know about both "how to compute factorial values" and "how to display progress", you could pass in a delegate:

public int Factorial(int number, Action<int> progressAction, int time = 0) {

... then call that progress action on each iteration of your loop (which is what I assume you do with the progress bar).

That improves separation of concerns. If you don't want to indicate progress in all cases, you could make progressAction default to null.

Another option is to invert the control completely, and consider Factorial as just a sequence of values - use an iterator block to do that easily:

public IEnumerable<int> Factorial()
{
    for (...)
    {
        // Do work
        yield return currentValue;
    }
}

You can impose time restrictions (which I assume is what the time parameter is for?) separately, and this way the caller gets to work out how many times to iterate and what to do with the results. The Factorial method only knows how to produce a sequence of factorial numbers.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @user1556775: Please see the (edited) rest of my answer though. Your design can be improved a lot in terms of separation of concerns. – Jon Skeet Jul 27 '12 at 06:30
0

ProgressBar ultimately derives from System.Object, so you can just write

public int Factorial(int number, System.Windows.Forms.Label l, 
    System.Windows.Forms.ProgressBar newprogressbar = null, int time=0)

To check in the method if it has been defined, just write

if (newprogressbar != null)
{
    // Do something with newprogressbar
}
Eric J.
  • 147,927
  • 63
  • 340
  • 553