imo the second one should not really say "args" as only one string[] is
passed. It could have been int[], object[], uint[], etc. But it is still
only one ref to an object (the array is the object which contains 0 or more
elements - the ref could also be null, but assume we know that.) You will
notice that "static void Main(string[] args)" passes command line args like
that. It does not need the params because that is the contract it defines.
It will take arguments at the cmdline and make a string[] from those. Using
params is really just a bit of sugar for the *caller to allow seperating
values via commas instead putting into an array first. Actually I don't
find a need to use params that much (if ever) because the mixmash between
the method signature and what the caller defines and you don't get the full
intellisense to explain and type each parm. Normally, you can find a way
around needing this or just use an array or other collection to begin with.
That said, people do use this as I am sure others will attest to.
The first one is little more interesting. If the caller supplies a bunch of
strings in the parms, then the clr will bunch them up into an string array
(using example below) and pass that. So it converts the arguments to one
array before the call, same as if you build the array yourself and passed
that. If the parm is not a valid type for the array or type can not be auto
converted to target type, then it will not even compile (see below.) hth
private void button50_Click(object sender, System.EventArgs e)
{
UseParams("one", "two", "three");
string[] myArray = new string[]{"four", "five"};
UseParams(myArray);
//UseParams("one", "two", "three", 4); //Does not compile.
UseParams("one", "two", "three", (4).ToString() );
UseParams2(1, 2, 3);
UseParams2((ushort)4, (ushort)5, (byte)Convert.ToUInt32("6"));
}
public static void UseParams(params string[] list)
{
for ( int i = 0 ; i < list.Length ; i++ )
Console.WriteLine(list
);
Console.WriteLine();
}
public static void UseParams2(params int[] list)
{
for ( int i = 0 ; i < list.Length ; i++ )
Console.WriteLine(list);
Console.WriteLine();
}
--
William Stacey, MVP
z_learning_tester said:
Hello,
I'm studying parameter arrays now and see what looks like a contradiction in
my book.
First it says that to pass any number of say object types to a method you
say:
int myMethod (params object [] O) {...}
//so basically you need to use the 'params' keyword.
But then later it says to pass any number of string arguements to function
main you say:
static void Main (string [] args) {...}
Did they make a typo where it should have a 'params' in there?
What if you pass it 2 string arguements? Would this one error out?
Thanks much,
Jeff