Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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 IronPDF library from Iron Software and explain how to use the params keyword and IronPDFto generate PDFs.
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
"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
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 List
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.
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
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
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
Syntax error as there is a type mismatch from the defined params 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
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
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
For any parameter with params argument is considered an optional parameter and can be called without passing parameters.
Create a new Console Application. Open Visual Studio, create new project and select console application type.
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
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.
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
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
In the above code, we are generating HTML document for cart items and then saving it as a PDF document using IronPDF.
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"
Provide your email ID to get a trial license delivered to your email ID.
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.
9 .NET API products for your office documents