Monday, July 16, 2007

Variable argument methods

Variable argument methods
sometimes a general purpose requirements is to provide a variable number of parameters to a common logical unit. 'params' keyword in c# helps you perform such sometiems difficult tasks.

only care that should be take while passing variable argument is the type of variable. if you fix the type, then it might become easy but it wont fulfill the variable argument feature.
we will discuss both options :

fixed argument type :

void Ex(params string[] args)
{
foreach(string ar in args)
{
Console.WriteLine(ar);
}
}

Ex("a","d","r","t");


different argument types :

void Ex(params object[] args)
{
foreach(object ar in args)
{
Console.WriteLine(ar);
}
}
//the implementation will be similar to printf function in c

Ex(1, 'a', "text");

ps: problem comes when you need to work on the args and compute some result, which needs the actual conversion on the args to their original type. to do that we need to pass the args type in sequence with actual args sequence, as a string.

void Ex(string sequentialArgsTypeList, params object[] args)
{
//convert each arg based on its corresponding type defined in 'sequentialArgsTypeList'
}
//the implementation will be similar to printf function in c

Ex("int,string,Employee", ob1, ob2, ob3);

No comments: