Default function parameter error

Aidan

New member
Joined
Apr 10, 2022
Messages
2
Programming Experience
Beginner
Hi, I have searched the internet and cannot find anything on how to set a variable as a default parameter. Here is and example of the function:
error:
using System;

int prePickedNum = 2;

void MyFunction(int num = prePickedNum)
{
    num += 1;
}

MyFunction();

The error is because I am trying to us a variable as the default parameter. Any help would be apreciated.
 
Why do you need default parameters in the first place? Default parameters are a compile time concept. Ii is to simplify code. Default parameters are not for runtime use. Imagine what kind of debugging hell it would be if default parameters changed each time your called a method. You would be dependent on side effects everywhere.
 
Optional parameters do what they do. If you don't want what they do then don't use them. Use something else that will do what you want, i.e. overload the method:

C#:
using System;

int prePickedNum = 2;

void MyFunction()
{
    MyFunction(prePickedNum);
}

void MyFunction(int num)
{
    num += 1;
}

MyFunction();
That will work exactly the same as an optional parameter as far as the calling code is concerned but it will use a variable if no explicit value is provided. Overloading has been around a lot longer than optional parameters in C#. The main advantage of optional parameters is that, if you have several of them, you can just write a single method instead of multiple overloads with all combinations of parameters.
 

Latest posts

Back
Top Bottom