SYSK 183: Variable Number of Parameters – the Right and the Wrong Way

If you need to create a function that takes in a variable (unknown at creation time) number of parameters, what programming construct should you use?

 

I’ve seen folks posting on the Internet solutions that use the __arglist keyword.  Note: this calling convention is not CLS compliant.  It might make it feel “cool” by using this “undocumented” feature…  But, the reason it’s not broadly talked about in the documentation, is because it is not recommended.  Instead, you should use the params keyword.  Besides being CLS compliant, it also produces cleaner code.  Compare for yourself:

 

public void Test(params object[] args)

{

    foreach (object item in args)

    {

        System.Diagnostics.Debug.WriteLine(item.ToString());

    }

}

public void Test(__arglist)

{

    ArgIterator iter = new ArgIterator(__arglist);

    while (iter.GetRemainingCount() > 0)

    {

        object item = TypedReference.ToObject(iter.GetNextArg());

        System.Diagnostics.Debug.WriteLine(item.ToString());

    }

}

Note: the Visual Studio intellisense will not show the required syntax for __arglist (it’ll show no parameters, but that wouldn’t compile), and it will display proper syntax for params