Welcome to MSDN Blogs Sign in | Join | Help

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 

 

 

Published Tuesday, August 22, 2006 5:17 AM by irenak

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

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

Tuesday, August 22, 2006 12:05 PM by hasanib
you should go on to talk about the purpose of __arglist :)

I remeber using it at a previous job to p/invoke variable argument functions such as sprintf and CString::Format.

# C# : Connaissez-vous les méthodes ayant un nombre de paramètres variables ?

Thursday, August 24, 2006 10:53 AM by .net is good... C# is better ;)
Cyril nous a récemment parlé des paramètres optionels et leur implémentation en C# en vu de l'utilisation...

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker