Reputation: 2543
For example, printf
in c can take any number of parameters like printf("%d %d %s %s...",a,b,c,d,...
) and is documented as below
printf( const char *format [, argument]... );
How can I define such functions in C#?
Upvotes: 2
Views: 148
Reputation: 49221
in c# the you'll use the params key word.
public static void UseParams2(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
Upvotes: 1
Reputation: 3901
private void Print(params object[] values)
{
foreach (var item in values)
{
Console.WriteLine(item);
}
}
this code will print to the console every item you'll send at the object array using the "params" keyword. you can call this method with as many parameters you like (or none).
link: http://msdn.microsoft.com/en-us/library/w5zay9db(v=vs.110).aspx
Upvotes: 1
Reputation: 62248
There are several approaches in this case:
You can define a type
that holds all fields you need to pass and return between methods. Better then simple object array
, cause it's typesafe.
You can define dictionary where place parameter names and values. Better then simple object array
, cause it's typesafe.
(This depends on quantity of the parameters, and on use logic of the code) You can define overrloads of the same function.
func A (AA aa)
func A(AA aa, BB bb =null)
func A(AA aa, BB bb = null, CC cc = null)
and so on...
Upvotes: 0
Reputation: 10840
use params object[] arg as the last argument. http://msdn.microsoft.com/en-us/library/w5zay9db%28v=vs.71%29.aspx see for more detail
Upvotes: 1
Reputation: 22979
Using the params keyword:
void WriteAll(params object[] args) {
for(int i = 0; i < args.Length; i++)
Console.WriteLine(args[i]);
}
args will be an array with all the arguments you pass. Note that it must be the last formal argument.
Upvotes: 8
Reputation: 4327
Just pass an object with your parameters
private void MyVoid(MyParameterObject params)
{
}
Upvotes: 0