C# Params (How It Works For Developers)

The params keyword in C# is a powerful feature in .NET that allows a method to accept a variable number of arguments. This can significantly simplify the syntax when calling methods that require a varying number of parameters. In this comprehensive guide, we will explore the params keyword in C#, its syntax, use cases, and best practices. Later in this article, we will introducethe IronPDFlibrary from Iron Software and explain how to use the params keyword and IronPDFto generate PDFs.

What is the C# Params argument type?

In the realm of C#, methods typically adhere to a predetermined set of parameters. Nevertheless, there exist situations where one might find themselves uncertain about the precise number of arguments destined for a method. Enter the "params" keyword, a solution that enables the specification of a method parameter capable of accommodating an array of arguments. This functionality proves invaluable when the developer is unsure about the exact number of arguments in advance, facilitating the passage of an indeterminate or optional number of parameters, all the same type, within a method declaration.

public class ParamsExample
{
    public void PrintMessages(params string[] messages)
    {
        foreach (var message in messages)
        {
            Console.WriteLine(message);
        }
    }
}
// Usage
class Program {
public static void main(){
var example = new ParamsExample();
example.PrintMessages("Hello", "World", "!");
}
// more examples
public static void AddItemsToShoppingBasket(params string[] items)
{
  // ....
}
public static void AddItemsSumToShoppingBasket(params int[] sum) // params int
{
  // ....
}
public class ParamsExample
{
    public void PrintMessages(params string[] messages)
    {
        foreach (var message in messages)
        {
            Console.WriteLine(message);
        }
    }
}
// Usage
class Program {
public static void main(){
var example = new ParamsExample();
example.PrintMessages("Hello", "World", "!");
}
// more examples
public static void AddItemsToShoppingBasket(params string[] items)
{
  // ....
}
public static void AddItemsSumToShoppingBasket(params int[] sum) // params int
{
  // ....
}
Public Class ParamsExample
	Public Sub PrintMessages(ParamArray ByVal messages() As String)
		For Each message In messages
			Console.WriteLine(message)
		Next message
	End Sub
End Class
' Usage
Friend Class Program
Public Shared Sub main()
Dim example = New ParamsExample()
example.PrintMessages("Hello", "World", "!")
End Sub
' more examples
Public Shared Sub AddItemsToShoppingBasket(ParamArray ByVal items() As String)
  ' ....
End Sub
Public Shared Sub AddItemsSumToShoppingBasket(ParamArray ByVal sum() As Integer) ' params int
  ' ....
End Sub
VB   C#

"AddItemsToShoppingBasket" method can be invoked with a variable number of arguments of string parameters. The params object keyword simplifies the syntax for the method call by allowing developers to pass the optional parameters directly, without explicitly creating an array input.

class Program {
AddItemsToShoppingBasket("cake", "pizza", "cold drink");
AddItemsToShoppingBasket("snacks", "burger");
AddItemsToShoppingBasket(); // Valid with zero parameters default value
}
class Program {
AddItemsToShoppingBasket("cake", "pizza", "cold drink");
AddItemsToShoppingBasket("snacks", "burger");
AddItemsToShoppingBasket(); // Valid with zero parameters default value
}
Friend Class Program
AddItemsToShoppingBasket("cake", "pizza", "cold drink")
AddItemsToShoppingBasket("snacks", "burger")
AddItemsToShoppingBasket() ' Valid with zero parameters default value
End Class
VB   C#

Considerations and Best Practices

Position Params at the End of Parameter List: A recommended practice is to situate the params parameter at the conclusion of the method's parameter list. This practice fosters clarity, mitigating confusion during method calls. Parameters requiring explicit values should precede the params for effective organization.

Explicitly Specify Non-params Parameters: When invoking a method with params, ensure explicit provision of values for non-params parameters. This practice prevents ambiguity and guarantees the accurate invocation of the method with the requisite number of arguments.

Exercise Caution to Prevent Ambiguity: Vigilance is key when utilizing params in methods with multiple overloads or parameters of the same type. The compiler may grapple with determining the appropriate method to invoke, potentially resulting in ambiguity errors.

Explore Alternative Approaches: While params offer convenience, consider alternative methods in certain scenarios. Utilizing collections such as Listcould be preferable for enhanced functionality or when passing named parameters aligns with your objectives.

Apply Judiciously to Relevant Scenarios: Deploy params judiciously in scenarios where the parameter count is variable and can fluctuate across distinct method calls. Reserve its usage for situations where the number of parameters is unpredictable, steering clear of its application when the parameter count is fixed and known.

One-Dimensional array for the parameter type

AddItemsToShoppingBasket can also be used by calling a one dimensional array.

// example
class Program {
public static void main()
{
var items = [] {"cold drink", "snack", "roll", }; // 1D string array
AddItemsToShoppingBasket(items); // works
AddItemsToShoppingBasket( "cold drink", "coke", "roll",); // same as above line
}
}
// example
class Program {
public static void main()
{
var items = [] {"cold drink", "snack", "roll", }; // 1D string array
AddItemsToShoppingBasket(items); // works
AddItemsToShoppingBasket( "cold drink", "coke", "roll",); // same as above line
}
}
' example
Friend Class Program
Public Shared Sub main()
Dim items = () {"cold drink", "snack", "roll"} ' 1D string array
AddItemsToShoppingBasket(items) ' works
AddItemsToShoppingBasket("cold drink", "coke", "roll",) ' same as above line
End Sub
End Class
VB   C#

Pass a comma-separated array of arguments of the same type

AddItemsToShoppingBasket can also be called by passing list/array of variables in the method call like below.

// example method signature
class Program {
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // comma separated values
AddItemsToShoppingBasket("snacks"); 
}
// example method signature
class Program {
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // comma separated values
AddItemsToShoppingBasket("snacks"); 
}
' example method signature
Friend Class Program
AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink") ' comma separated values
AddItemsToShoppingBasket("snacks")
End Class
VB   C#

Pass an array of the defined type

The array should contain the same type defined in the params method, else error is thrown as below

// example
AddItemsToShoppingBasket("snacks",2,"burger"); // error 
AddItemsToShoppingBasket(2,3,4); // error as params type is string
// example
AddItemsToShoppingBasket("snacks",2,"burger"); // error 
AddItemsToShoppingBasket(2,3,4); // error as params type is string
' example
AddItemsToShoppingBasket("snacks",2,"burger") ' error
AddItemsToShoppingBasket(2,3,4) ' error as params type is string
VB   C#

Syntax error as there is a type mismatch from the defined params in the method.

Always the Last parameter in the Method

No additional parameters are permitted after the params parameter in a method signature declaration, and only one params argument is permitted in a method parameters declaration.

Method signature should have params defined at the last, no parameters are permitted after. Defining so leads to compilation errors.

class program {
static void Main(string[] args){
// example 1
   public static void AddItemsToShoppingBasket(double total, params string[] items)
   {
     // ....
   } // This works
}
}
example 2
static void Main(string[] args){
   public static void AddItemsToShoppingBasket(double total, int total, params string[] items)
   {
     // ....
   } // This works
}
// example 3 error scenario
static void Main(string[] args){
   public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total)
   {
     // error
   } // params keyword is defined as first parameter, needs to be at the last.
}
class program {
static void Main(string[] args){
// example 1
   public static void AddItemsToShoppingBasket(double total, params string[] items)
   {
     // ....
   } // This works
}
}
example 2
static void Main(string[] args){
   public static void AddItemsToShoppingBasket(double total, int total, params string[] items)
   {
     // ....
   } // This works
}
// example 3 error scenario
static void Main(string[] args){
   public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total)
   {
     // error
   } // params keyword is defined as first parameter, needs to be at the last.
}
Friend Class program
Shared Sub Main(ByVal args() As String)
' example 1
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'   public static void AddItemsToShoppingBasket(double total, params string[] items)
'   {
'	 ' ....
'   } ' This works
End Sub
End Class
example 2 Shared Sub Main(ByVal args() As String)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'   public static void AddItemsToShoppingBasket(double total, int total, params string[] items)
'   {
'	 ' ....
'   } ' This works
End Sub
' example 3 error scenario
Shared Sub Main(ByVal args() As String)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'   public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total)
'   {
'	 ' error
'   } ' params keyword is defined as first parameter, needs to be at the last.
End Sub
VB   C#

Only One params keyword

Only one params parameter in a method signature is allowed. The compiler throws an error if more than one params keyword is found in the method signature.

//only one params keyword example
class Program {
static void Main(string[] args){
public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
{
} // Compiler error, This does not work. 
}
}
//only one params keyword example
class Program {
static void Main(string[] args){
public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
{
} // Compiler error, This does not work. 
}
}
'only one params keyword example
Friend Class Program
Shared Sub Main(ByVal args() As String)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
'{
'} ' Compiler error, This does not work.
End Sub
End Class
VB   C#

You can pass no arguments

If a method has only parameter with params keyword then it can be called without any arguments like the below and the compiler won't throw an error.

AddItemsToShoppingBasket(); // Works
AddItemsToShoppingBasket(); // Works
AddItemsToShoppingBasket() ' Works
VB   C#

For any parameter with params argument is considered an optional parameter and can be called without passing parameters.

Code Example

Create a new Console Application. Open Visual Studio, create new project and select console application type.

C# Params (How It Works For Developers): Figure 1 - Creating a new console application

Now add the below code.

class Program {
Console.WriteLine("Params demo");
List<string> cart = new List<string>();
void AddItemsToShoppingBasket(params string[] samples)
{
    for (int i = 0; i < samples.Length; i++)
    {
        cart.Add(samples[i]);
    }
}
// caller code
static void Main(string[] args) {
Console.WriteLine("Enter the cart items as comma separated values");
var itemsString = Console.ReadLine();
if (itemsString != null)
{
    var items = itemsString.Split(",").ToArray();
    AddItemsToShoppingBasket(items);
}
AddItemsToShoppingBasket("Sample1", "Sample2");
Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("Display Cart");
foreach (var item in cart)
{
    Console.WriteLine(item);
}
}
}
class Program {
Console.WriteLine("Params demo");
List<string> cart = new List<string>();
void AddItemsToShoppingBasket(params string[] samples)
{
    for (int i = 0; i < samples.Length; i++)
    {
        cart.Add(samples[i]);
    }
}
// caller code
static void Main(string[] args) {
Console.WriteLine("Enter the cart items as comma separated values");
var itemsString = Console.ReadLine();
if (itemsString != null)
{
    var items = itemsString.Split(",").ToArray();
    AddItemsToShoppingBasket(items);
}
AddItemsToShoppingBasket("Sample1", "Sample2");
Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("Display Cart");
foreach (var item in cart)
{
    Console.WriteLine(item);
}
}
}
Friend Class Program
Console.WriteLine("Params demo")
Dim cart As New List(Of String)()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'void AddItemsToShoppingBasket(params string[] samples)
'{
'	for (int i = 0; i < samples.Length; i++)
'	{
'		cart.Add(samples[i]);
'	}
'}
' caller code
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static void Main(string[] args)
'{
'Console.WriteLine("Enter the cart items as comma separated values");
'var itemsString = Console.ReadLine();
'if (itemsString != Nothing)
'{
'	var items = itemsString.Split(",").ToArray();
'	AddItemsToShoppingBasket(items);
'}
'AddItemsToShoppingBasket("Sample1", "Sample2");
'Console.WriteLine("-------------------------------------------------------");
'Console.WriteLine("Display Cart");
'foreach (var item in cart)
'{
'	Console.WriteLine(item);
'}
'}
End Class
VB   C#

Output

C# Params (How It Works For Developers): Figure 2 - Above code output

Introducing IronPDF

IronPDF C# PDF library from Iron Softwareis a versatile library that can read, write, and manage PDF documents in C#. It supports all kinds of modern application development like Mobile, Website, Desktop, Docker, etc. And also supports different OS like Windows, Linux, Unix, etc. It does not depend on native OS methods.

Installation

IronPDF library can be installed using the NuGet package manager console with the below command or using the Visual Studio package manager.

dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
VB   C#

Using IronPDF to Generate a PDF

Now we will use the IronPDF to generate the PDF document from the above example.

class program
{
public static void main()
{
Console.WriteLine("IronPDF to generate the PDF document for Params Example");
List<string> cart = new List<string>();
void AddItemsToShoppingBasket(params string[] items)
{
    for (int i = 0; i < items.Length; i++)
    {
        cart.Add(items[i]);
    }
}
// take input from console
Console.WriteLine("Enter the cart items as comma seperated values");
var itemsString = Console.ReadLine();
// read the items
if (itemsString != null)
{
    var items = itemsString.Split(",").ToArray();
    AddItemsToShoppingBasket(items);
}
// add to cart
AddItemsToShoppingBasket("Sample1", "Sample2");
Console.WriteLine("------------------------------------------------");
Console.WriteLine("Display Cart");
Console.WriteLine("------------------------------------------------");
string name = "Sam";
var count = cart.Count;
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" +
string.Join("\n", cart.Select(x => $"<p>{x}</p>"))
+ @"
</body>
</html>";
// Create a new PDF document
var pdfDoc = new ChromePdfRenderer();
pdfDoc.RenderHtmlAsPdf(content).SaveAs("cart.pdf");
}
}
class program
{
public static void main()
{
Console.WriteLine("IronPDF to generate the PDF document for Params Example");
List<string> cart = new List<string>();
void AddItemsToShoppingBasket(params string[] items)
{
    for (int i = 0; i < items.Length; i++)
    {
        cart.Add(items[i]);
    }
}
// take input from console
Console.WriteLine("Enter the cart items as comma seperated values");
var itemsString = Console.ReadLine();
// read the items
if (itemsString != null)
{
    var items = itemsString.Split(",").ToArray();
    AddItemsToShoppingBasket(items);
}
// add to cart
AddItemsToShoppingBasket("Sample1", "Sample2");
Console.WriteLine("------------------------------------------------");
Console.WriteLine("Display Cart");
Console.WriteLine("------------------------------------------------");
string name = "Sam";
var count = cart.Count;
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" +
string.Join("\n", cart.Select(x => $"<p>{x}</p>"))
+ @"
</body>
</html>";
// Create a new PDF document
var pdfDoc = new ChromePdfRenderer();
pdfDoc.RenderHtmlAsPdf(content).SaveAs("cart.pdf");
}
}
Imports Microsoft.VisualBasic

Friend Class program
Public Shared Sub main()
Console.WriteLine("IronPDF to generate the PDF document for Params Example")
Dim cart As New List(Of String)()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'void AddItemsToShoppingBasket(params string[] items)
'{
'	for (int i = 0; i < items.Length; i++)
'	{
'		cart.Add(items[i]);
'	}
'}
' take input from console
Console.WriteLine("Enter the cart items as comma seperated values")
Dim itemsString = Console.ReadLine()
' read the items
If itemsString IsNot Nothing Then
	Dim items = itemsString.Split(",").ToArray()
	AddItemsToShoppingBasket(items)
End If
' add to cart
AddItemsToShoppingBasket("Sample1", "Sample2")
Console.WriteLine("------------------------------------------------")
Console.WriteLine("Display Cart")
Console.WriteLine("------------------------------------------------")
Dim name As String = "Sam"
Dim count = cart.Count
Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} items in the cart.</p>
" & String.Join(vbLf, cart.Select(Function(x) $"<p>{x}</p>")) & "
</body>
</html>"
' Create a new PDF document
Dim pdfDoc = New ChromePdfRenderer()
pdfDoc.RenderHtmlAsPdf(content).SaveAs("cart.pdf")
End Sub
End Class
VB   C#

In the above code, we are generating HTML document for cart items and then saving it as a PDF document using IronPDF.

Output

C# Params (How It Works For Developers): Figure 3 - PDF Output from the code above

Licensing (Free Trial Available)

IronPDF requires a license key to work in production. A trial key can be obtained from the license page here. Place the key in appsettings.json.

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

Provide your email ID to get a trial license delivered to your email ID.

Conclusion

The params keyword in C# with .NET 8 offers a flexible way to handle methods that require a variable number of parameters. It simplifies the method calls and makes the code more readable and maintainable. Together with IronPDF, it is a great combination of skills for any programmer to write clean code.