Introduction
In this tip, we will discuss the params keyword in C# and how to pass a variable number of parameters to a method.
Problem
Suppose there is a method GetConcat (string name) which takes one parameter of string type. And method returns a merge string of some hard-code text, separator, and name (name of a person). It will work fine when we will pass two parameters to this method. But if a user wants to pass one more parameter (name of a person) like GetConcat (string name, string name2), then this method will not work perfectly. Again another user wants to pass 5 parameters (name of persons), then it would be difficult to write different methods for different users.
Solution
C# provides an elegant solution to resolve the preceding problem by using the params keyword. Using params, we can pass a variable number of parameters to a method.
There are some restrictions using the params keyword.
- You can only use the params keyword for one parameter in your method declaration.
- Params must be always the last parameter in a method.
Using Code
In the following code, GetConcat() is taking two params, one is a separator, and another is a string array with params.
public string GetConcat(params string[] names)
{
string result = "";
if (names.Length > 0)
{
result += names[0];
}
for (int i = 1; i < names.Length; i++)
{
result += ", " + names[i];
}
return result;
}
Call the method
string tempResult = GetConcat("Ajay", "Bijay", "Sanjay");
Here we are passing 4 parameters for names. Run-time compiler creates a temp array and holds all names. After that, pass GetConcat().
Output. Ajay, Bijay, Sanjay
We can resolve the above problems without using params, but how? We can declare an array of string types and pass that variable to your method. Here is the code.
public string GetConcat(string[] names)
{
string result = "";
if (names.Length > 0)
{
result += names[0];
}
for (int i = 1; i < names.Length; i++)
{
result += ", " + names[i];
}
return result;
}
string[] names = { "Ajay", "Bijay", "Sanjay" };
string tempResult = GetConcat(names);
You will get the same result here. Again another question here is why we will use params. The reason is in params; we didn't create any array. We pass arguments as comma separated. But here, we need to define an array and then pass that variable to the method.
Suppose you don't know about the type of data you are passing to the method, then you can use the object. Here is the code.
public static string GetConcat(params object[] names)
{
string result = "";
if (names.Length > 0)
{
result += names[0];
}
for (int i = 1; i < names.Length; i++)
{
result = result + ", " + names[i];
}
return result;
}
The best example of params in a method is.
-
string.Concat()
-
string.Format()
In this tip, we discussed how to pass a variable number of parameters to a method. Hope it helps you.