Use a function to define an optional parameter
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
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);
}
Is it possible to use the return value of a function instead of a specific value as optional parameter in a function?
No. It is not possible. The C# programming guide on Optional Arguments says:
A default value must be one of the following types of expressions:
a constant expression;
an expression of the form
new ValType()
, whereValType
is a value type, such as an enum or a struct;an expression of the form
default(ValType)
, whereValType
is a value type.
See other answers for alternative solutions.