Used Named Optional Parameters for Method

  • A+
Category:Languages

I have a method where I have several optional boolean parameters, different properties of an object will be given a value based on which parameters are true.

Here is the method for context:

public static AutoPatientLookup InitializeTestPatientInfo(bool SSN = false, bool PatientNumber = false, bool Gender = false) {     AutoPatientLookup TestAPIParameters = new AutoPatientLookup();     TestAPIParameters.FirstName = "First";     TestAPIParameters.LastName = "Last";     TestAPIParameters.DOB = "4/9/1953";     TestAPIParameters.PracticeID = 11071;      if (SSN)     {         TestAPIParameters.SSN = 000010281;     }     if (PatientNumber)     {         TestAPIParameters.PatientNumber = 458;     }     if (Gender)     {         TestAPIParameters.Gender = "F";     }      return TestAPIParameters; } 

However, sometimes I want the second or third boolean parameter to be true but I'm unable to designate that as the parameter I want to switch without explicitly stating true or false for the preceding parameters.

This if I want to initialize an AutoPatientLookup object that has a value for its gender property, I would have to call it like this:

InitializeTestPatientInfo(false,false,true); 

I tried something along the lines of

InitializeTestPatientInfo(Gender = true); 

and

InitializeTestPatientInfo(bool Gender = true); 

but nothing seems to work. Is there a correct syntax for accomplishing for what I'm attempting? Even though the initialization syntax isn't very inconvenient when there are only three boolean parameters this could be more applicable if there are dozens.


You can name your parameter that you are assigning:

Do this instead

InitializeTestPatientInfo(Gender: true); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: