Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a function to define an optional parameter

Is it possible to use the return value of a function instead of a specific value as optional parameter in a function? For example instead of:

public void ExampleMethod(int a, int b, int c=10)
{
}

I want something like

private int ChangeC(int a, int b)
{
    return a+b;
}

public void ExampleMethod(int a, int b, int c=ChangeC(a,b))
{
}
like image 963
Johannes Pertl Avatar asked Dec 11 '19 12:12

Johannes Pertl


2 Answers

No this is not possible. For a parameter to be optional the value must be a compile time constant. You can however overload the method like so:

private int ChangeC(int a, int b)
{
    return a + b;
}

public void ExampleMethod(int a, int b, int c) {}

public void ExampleMethod(int a, int b)
{
    ExampleMethod(a, b, ChangeC(a, b));
}

This way you don't have to deal with nullable value types

like image 52
MindSwipe Avatar answered Sep 30 '22 18:09

MindSwipe


One of the ways:

private int ChangeC(int a, int b)
{
    return a+b; 
} 

public void ExampleMethod(int a, int b, int? c=null)
{
    c = c ?? ChangeC(a,b);
}
like image 25
Gleb Avatar answered Sep 30 '22 18:09

Gleb