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"});
}
}
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.
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.
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)
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.
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" });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With