Common Type System—Variable Argument Methods


Jump to: navigation, search
Visual C# Tutorials
.NET Framework Tutorials

Common Type System

© 2006 Wiley Publishing Inc.

Variable Argument Methods

Ever since the old C-style printf function has there been support for variable-length arguments in programming languages. This permits methods to accept a number of arguments whose count is not known at compile time. Callers of the method are free to pass an unbounded set of arguments at invocation. The method body itself uses special constructs to extract and work with such arguments.

The CTS actually supports variable arguments directly in the IL, through the use of the vararg method modifier. Such methods then use the arglist instruction to obtain an instance of System.ArgIterator for purposes of walking the incoming list of arguments. The method signature doesn’t even mention the type of arguments.

However, many languages (e.g., C#) use an entirely different convention for variable argument methods. These languages use arrays to represent the variable portion of their arguments and mark the method with the System.ParamArrayAttribute custom attribute. The calling convention is such that callers passing variable-length arguments pack them into an array, and the method itself simply works with the array. For example, consider this example in C#, using the params keyword:

void PrintOut(params object[] data)
{
   foreach (object o in data)
   Console.WriteLine(o);
}
PrintOut("hello", 5, new DateTime(10, 10, 1999));

C# will turn the invocation to PrintOut into IL, which constructs an array, packs the string "Hello", the int 5, and the DateTime representing 10/10/1999 into it, and passes that as the data argument. The PrintOut function then just deals with data as any ordinary array.


Previous_Page_.gif Next_Page_.gif





Personal tools
Share this page
  • del.icio.us
  • Facebook
  • StumbleUpon