Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set optional parameters default value based on other parameters

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.

like image 237
MaxRecursion Avatar asked Dec 14 '22 14:12

MaxRecursion


1 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");
like image 122
Jason W Avatar answered Dec 16 '22 04:12

Jason W