I have a method with a ton of parameters. Some of them are optional. So, in order to use this method easily I use the optional parameter feature.
Moreover, this method builds a Dictionary<string,string>
with name of parameter as key of the dictionary and value of the parameter as value of the dictionary for non-null parameters only.
Here is the method :
public string CreateParameterDictionary(
string id,
string firstName,
string lastName,
string address,
string postalCode,
string lorem = null,
string ipsum = null,
string dolor = null,
//...
string sit = null,
string amet = null)
{
if (String.IsNullOrWhiteSpace(id) ||
String.IsNullOrWhiteSpace(firstName) ||
String.IsNullOrWhiteSpace(lastName) ||
String.IsNullOrWhiteSpace(address) ||
String.IsNullOrWhiteSpace(postalCode))
{
throw new ArgumentNullException($"nameof((id) nameof(firstName) nameof(lastName) nameof(address) nameof(postalCode)");
}
Dictionary<string,string> parametersDictionary = new Dictionary<string, string>();
parametersDictionary.Add(nameof(((id),((id);
parametersDictionary.Add(nameof(firstName),firstName);
parametersDictionary.Add(nameof(lastName),lastName);
parametersDictionary.Add(nameof(address),address);
parametersDictionary.Add(nameof(postalCode),postalCode);
if (!String.IsNullOrWhiteSpace(lorem)) parametersDictionary.Add(nameof(lorem), lorem);
if (!String.IsNullOrWhiteSpace(ipsum)) parametersDictionary.Add(nameof(ipsum), ipsum);
if (!String.IsNullOrWhiteSpace(dolor)) parametersDictionary.Add(nameof(dolor), dolor);
//...
if (!String.IsNullOrWhiteSpace(sit)) parametersDictionary.Add(nameof(sit), sit);
if (!String.IsNullOrWhiteSpace(amet)) parametersDictionary.Add(nameof(amet), amet);
return parametersDictionary;
}
Can be called with named parameters as:
CreateParameterDictionary(5, "Dexter, "Morgan", "Miami", 12345, dolor: 5);
As you can see, the method is a little bit verbose. I want to know if there is a more concise way to write it (without reflection)
Thank you !
EDIT
Thank you for your answers However, I'm not clear in my question. Just a precision :
- parameter names in my real method are not param1, param2 etc. but more business name like id, firstName, lastName, address1 = null. Like this when we use this method, it's more easy to know which parameter is mandatory or not. Before this I used params string[] but when I used it i can't have the name of the parameter.
Hope my explanation is more clear now.