Norbert Norbertson Norbert Norbertson - 4 months ago 38
C# Question

C# simple way to build params list for variable number of params

I have a method that takes this parameter

params string[] additionalParameters

I am building it like this:

qsParams = new string[] {"k=" + k, "l=" + l, "o=" + o, "s=" + s, "t=" + t, "h=" + h, "exp=" + exp };

These are url params. The problem is I only want to add parameters where the variables are not null or empty.

I can do this kind of thing:

if (string.IsNullOrEmpty(k))
qsParams = new string[] {"l=" + l, "o=" + o, "s=" + s, "t=" + t, "h=" + h, "exp=" + exp };

But that's going to get complicated and ugly trying to handle all the different permutations of empty variables.

Can anyone suggest a simple way to add the params if there are not null? Perhaps a list that I can convert to a params []string?

    public static void Main(string[] args)

        List<string> parameters = new List<string>();

        string k = "a";
        string l = null;

        AddParam("k", k, parameters);
        AddParam("l", l, parameters);

        string[] result = parameters.ToArray();

    public static void AddParam(string paramName, string paramValue, List<string> parameters)
        if (string.IsNullOrEmpty(paramValue))

        parameters.Add(paramName + "=" + paramValue);

You can try something like this.