top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Can we create a function in C# which can accept varying number of arguments?

0 votes
Can we create a function in C# which can accept varying number of arguments?
posted May 23, 2017 by Amit Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Yes we can create it. The classic example wourld be the params object[] args:

//Allows to pass in any number and types of parameters

public static void Program(params object[] args)

A typical usecase would be passing parameters in a command line environment to a program, where you pass them in as strings. The program has then to validate and assign them correctly.


Only one params keyword is permitted per method
It has to be the last parameter.
EDIT: After I read your edits, I made mine. The part below also covers methods to achieve variable numbers of arguments, but I think you really were looking for the params way.

Also one of the more classic ones, is called method overloading. You've probably used them already a lot:

//both methods have the same name and depending on wether you pass in a parameter
//or not, the first or the second is used.
public static void SayHello() {
public static void SayHello(string message) {

Last but not least the most exiting one: Optional Arguments

//this time we specify a default value for the parameter message
//you now can call both, the method with parameter and the method without.
public static void SayHello(string message = "Hello") {
answer May 24, 2017 by Shweta Singh
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.