Search code examples
c#conventionsoptional-parameters

What's the convention when it comes to functions with a lot of optional parameters?


I have a simple HttpsGet function that takes ~20 optional parameters.

Right now I'm thinking between making every parameter optional and having the user create a custom Options object that they will use with the function. Creating 200 overloads is out of the question.

What would be the best way about making the function readable and easy to use for other users? Am I missing another solution?

Here's a simplified version of the code for the sake of readability.

static List<Assignments> GetAllAssignments([Optional] string levels, [Optional] string passed, [Optional] stringresurrected)
{               
    var json = Get($"assignments?{levels}&{passed}&{resurrected}");
    var assignments = JsonConvert.DeserializeObject<CollectionResponse<Assignments>>(json).Data;
    return assignments;            
}

Solution

  • It's usually best to have a "Options Object" that you pass this in instead of the individual values. Otherwise it can be quite easy for callers to pass the wrong value.

    static List<LevelProgression> GetLevelProgressions(LevelProgressionOptions options) 
    { 
    }
    

    Where the options might look like this

    public class LevelProgressionOptions
    {
        public LevelProgressionOptions()
        {
            // Set any default values
            SomeProperty = 1;
        }
    
       public int SomeProperty { get; set; }
       public string AnotherOption { get; set; }
       //  other values omitted
    }