I have a method with optional parameters. Im trying to see how far i can get overloads of all possibilities.

public static int PrintMenu(string message = "Choose an option....", string errorMessage = "error", bool clearScreen = true, params string[] list)

The most important argument is the string array. Is it possible to do something like following if i want to just change one of the named parameters? :

PrintMenu(errorMessage: "bad input", list : "listItem 1", "listItem 2", "listItem 3");

2 Answers

Kryptos On Best Solutions

params are a syntactic sugar that hides the use of an array. If you want to name it explicitly, you need to instantiate the array.

PrintMenu(errorMessage: "bad input", list: new[] { "listItem 1", "listItem 2", "listItem 3" });

That said, I would advise against over-using named parameters and params. Often it is a sign of a code smell with a method that takes too many parameters and/or performs too many tasks. It also makes it harder to use or read afterwards.

That's why I prefer to explicitly declare overloads and only use optional parameters for obvious flags (usually boolean) while limiting it to at most two such arguments.

Tim On

Yes, you can. Do it like this

PrintMenu(errorMessage: "Bad input", list: new string[] { "list item 1", "list item 2"});