8

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))
{
}
3
  • 4
    No, because the parameters for that method do not exist in that context. You could just use it on the first line of your method: c = c ?? ChangeC(a,b) Commented Dec 11, 2019 at 12:22
  • Please give an example in pseudo code. It is a bit unclear what you want to achieve. Commented Dec 11, 2019 at 12:23
  • You could have two overloads of the method - one with three parameters & one with two that calls the first using the results of the function call as the third parameter Commented Dec 11, 2019 at 12:25

3 Answers 3

16

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

Sign up to request clarification or add additional context in comments.

Comments

8

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);
}

Comments

3

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(), where ValType is a value type, such as an enum or a struct;

  • an expression of the form default(ValType), where ValType is a value type.

See other answers for alternative solutions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.