Related Entries

Is ADO.Net portable?
Oracle with C#
Slashdot: Java vs .Net
C# day 3
Mozilla intentionally breaks ASP.Net pages?

« Toshiba e355
» Blaster laster

Variable number of function arguments in C#

Unlike what I thought last week, this is possible in C#

During the training last week, my instructor was quiet sure that you cannot define a function that takes in multiple number of arguments, like **kw in C or Python.

Further research on MSDN reveals that it is indeed possible to do that with C#. In short, you use the keyword params to achieve this.

You can use only one params in the function definition. In practice, it is similar to passing an array. However, if you define your params as an array of objects, you can pass objects of different types too.

Googling reveals Java is thinking about implementing the same thing in JSR 65.

  1. Note that using **kw in Python makes kw a _dictionary_ of keyword arguments and not just a list. C#'s params seems to be equivalent to Python's *args.

    Posted by: Matt Goodall on August 28, 2003 06:54 PM
  2. I am trying to write a crude version of sscanf in c# (as far as I know c# doesn't have a sscanf). Here is the fn. The problem is that params passes arguments by value and I can't use the ref keyword with params. How to pass by reference then?


    static void sscanf(string input, string format, params object[] paramlist)
    {
    string pattern = @"\b\S+\b";
    MatchCollection matches1 = Regex.Matches(input, pattern);
    MatchCollection matches2 = Regex.Matches(format, @"\b\S+\b");
    for(int i = 0; i < matches1.Count; i++)
    {
    if (matches2[i].Value == "s")
    paramlist[i] = matches1[i].Value;
    else if (matches2[i].Value == "d")
    {
    try
    {
    int ii = int.Parse(matches1[i].Value);
    paramlist[i] = ii;
    }
    catch (Exception exc)
    {
    Console.WriteLine(exc.Message);
    }
    }
    else if (matches2[i].Value == "f" || matches2[i].Value == "lf")
    {
    try
    {
    double dd = double.Parse(matches1[i].Value);
    paramlist[i] = dd;
    }
    catch (Exception exc)
    {
    Console.WriteLine(exc.Message);
    }
    }
    }
    }

    Posted by: sid jain on April 23, 2004 05:25 AM
  3. Is there any other way of passing variable arguments to function other than using params. I do not want to use params in my function, but would like to use some other way of passing variable argument. Please let me know if you know any.

    Regards,
    Sunil.

    Posted by: Sunil on September 9, 2004 12:26 AM
//-->