W.Harr
W.Harr

Reputation: 303

Used Named Optional Parameters for Method

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.

Upvotes: 2

Views: 193

Answers (3)

Stefan Schmid
Stefan Schmid

Reputation: 1042

Try

InitializeTestPatientInfo(Gender: true);

Upvotes: 7

bman7716
bman7716

Reputation: 713

You can name your parameter that you are assigning:

Do this instead

InitializeTestPatientInfo(Gender: true);

Upvotes: 6

Ryan S
Ryan S

Reputation: 531

The syntax you want to use is:

InitializeTestPatientInfo(Gender: true);

Upvotes: 8

Related Questions