Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly keyword 'params' work?

The following code sample prints:

T
T[]
T[]

While first two lines are as expected, why compiler selected param array for a regular array?

public class A
{
    public void Print<T>(T t)
    {
        Console.WriteLine("T");
    }

    public void Print<T>(params T[] t)
    {
        Console.WriteLine("T[]");
    }
}

class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        a.Print("string");
        a.Print("string","string");
        a.Print(new string[] {"a","b"});
    }
}
like image 442
Prankster Avatar asked Apr 02 '09 22:04

Prankster


People also ask

What does the params keyword do?

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

What is params keyword in C#?

Params is an important keyword in C#. It is used as a parameter which can take the variable number of arguments. Important Point About Params Keyword : It is useful when programmer don't have any prior knowledge about the number of parameters to be used.

How do you pass keyword arguments in Python?

In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols: *args (Non Keyword Arguments) **kwargs (Keyword Arguments)


2 Answers

Under the hood

a.Print("string","string");

is just syntactic sugar for

a.Print(new string[]{"string","string"});

EDIT: Like I said, the params keyword only automagically creates the array for you, you tell the compiler: either accept an array of T directly or use the X input params to construct that array.

like image 162
arul Avatar answered Oct 06 '22 20:10

arul


It addition to what others have said, the params keyword also causes a ParamArrayAttribute to the generated for array parameter. So, this...

public void Print<T>(params T[] t) { }

Is generated by the compiler as...

public void Print<T>([ParamArray] T[] t); { }

It is that attribute which indicates to the compiler and the IDE that the method can be called using simpler syntax...

a.Print("string", "string");

rather than...

a.Print(new string[] { "string", "string" });
like image 22
Dustin Campbell Avatar answered Oct 06 '22 21:10

Dustin Campbell