Set optional parameters default value based on other parameters

Viewed 1158

I want to achieve following scenario:

Method:

public void Process(Request request, string statusCode=request.statusCode, string statusVal=request.statusVal) 
{ 
... 
}

Obviously above construct does not work in C#.

So in this case method process takes 3 parameters where calling parameter may or may not pass statusCode and/or statusVal in arguments.

When the values are not passed it should take the values from request object as default value. In short can the default value of optional parameters be dynamic or based on another compulsory parameter.

2 Answers

Here is how you can use optional parameters as described:

public void Process(Request request, string statusCode = null, string statusVal= null) 
{ 
    statusCode = statusCode ?? request.statusCode;
    statusVal = statusVal ?? request.statusVal;
    ... 
}

Now you can call it any of these ways:

  • Process(request);
  • Process(request, "code");
  • Process(request, "code", "val");
  • Process(request, statusCode: "code");
  • Process(request, statusVal: "val");

You can't use optional parameters like this. That's why I would suggest overloading the method. Could be look like this.

public void Process(Request request) 
{ 
    Process(request, request.statusCode, request.statusVal);
}

public void Process(Request request, string statusCode, string statusVal) 
{ 
    //your logic
}

In this case you can call the method with the Request only or specific statusCode and statusVal and both will have the same logic.

For further information have a look at C# in Depth: Overloading

Related