Defining functions which can take a lot of parameters in C#

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

Answers (6)

Yochai Timmer
Yochai Timmer

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

Tamir
Tamir

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

Tigran
Tigran

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

ZafarYousafi
ZafarYousafi

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

BlackBear
BlackBear

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

JohnnBlade
JohnnBlade

Reputation: 4327

Just pass an object with your parameters

private void MyVoid(MyParameterObject params)
{

}

Upvotes: 0

Related Questions