Skip to footer content
.NET HELP

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 introduce the IronPDF library from Iron Software and explain how to use the params keyword and IronPDF to 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 of the same type, within a method declaration.

public class ParamsExample
{
    // Method accepting a variable number of string arguments using the params keyword
    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)
    {
        // Implementation to add items to a shopping basket
    }

    public static void AddItemsSumToShoppingBasket(params int[] sum) // Using params with int
    {
        // Implementation to add sum of items to the shopping basket
    }
}
public class ParamsExample
{
    // Method accepting a variable number of string arguments using the params keyword
    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)
    {
        // Implementation to add items to a shopping basket
    }

    public static void AddItemsSumToShoppingBasket(params int[] sum) // Using params with int
    {
        // Implementation to add sum of items to the shopping basket
    }
}
Public Class ParamsExample
	' Method accepting a variable number of string arguments using the params keyword
	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)
		' Implementation to add items to a shopping basket
	End Sub

	Public Shared Sub AddItemsSumToShoppingBasket(ParamArray ByVal sum() As Integer) ' Using params with int
		' Implementation to add sum of items to the shopping basket
	End Sub
End Class
$vbLabelText   $csharpLabel

The AddItemsToShoppingBasket method can be invoked with a variable number of arguments of string parameters. The params 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
{
    public static void Main()
    {
        AddItemsToShoppingBasket("cake", "pizza", "cold drink");
        AddItemsToShoppingBasket("snacks", "burger");
        AddItemsToShoppingBasket(); // Valid even with zero parameters, using default value
    }
}
class Program
{
    public static void Main()
    {
        AddItemsToShoppingBasket("cake", "pizza", "cold drink");
        AddItemsToShoppingBasket("snacks", "burger");
        AddItemsToShoppingBasket(); // Valid even with zero parameters, using default value
    }
}
Friend Class Program
	Public Shared Sub Main()
		AddItemsToShoppingBasket("cake", "pizza", "cold drink")
		AddItemsToShoppingBasket("snacks", "burger")
		AddItemsToShoppingBasket() ' Valid even with zero parameters, using default value
	End Sub
End Class
$vbLabelText   $csharpLabel

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 offers convenience, consider alternative methods in certain scenarios. Utilizing collections such as List<T> could 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 it with a one-dimensional array.

class Program
{
    public static void Main()
    {
        var items = new string[] { "cold drink", "snack", "roll" }; // 1D string array
        AddItemsToShoppingBasket(items); // Works as expected
        AddItemsToShoppingBasket("cold drink", "coke", "roll"); // Similar result to the above line
    }
}
class Program
{
    public static void Main()
    {
        var items = new string[] { "cold drink", "snack", "roll" }; // 1D string array
        AddItemsToShoppingBasket(items); // Works as expected
        AddItemsToShoppingBasket("cold drink", "coke", "roll"); // Similar result to the above line
    }
}
Friend Class Program
	Public Shared Sub Main()
		Dim items = New String() { "cold drink", "snack", "roll" } ' 1D string array
		AddItemsToShoppingBasket(items) ' Works as expected
		AddItemsToShoppingBasket("cold drink", "coke", "roll") ' Similar result to the above line
	End Sub
End Class
$vbLabelText   $csharpLabel

Pass a Comma-Separated Array of Arguments of the Same Type

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

class Program
{
    public static void Main()
    {
        // Example method signature
        AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // Comma separated values
        AddItemsToShoppingBasket("snacks");
    }
}
class Program
{
    public static void Main()
    {
        // Example method signature
        AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink"); // Comma separated values
        AddItemsToShoppingBasket("snacks");
    }
}
Friend Class Program
	Public Shared Sub Main()
		' Example method signature
		AddItemsToShoppingBasket("snacks", "burger", "snacks", "burger", "cold drink") ' Comma separated values
		AddItemsToShoppingBasket("snacks")
	End Sub
End Class
$vbLabelText   $csharpLabel

Pass an Array of the Defined Type

The array should contain the same type defined in the params method; otherwise, an error is thrown.

// Example that results in an error
AddItemsToShoppingBasket("snacks", 2, "burger"); // Error due to type mismatch
AddItemsToShoppingBasket(2, 3, 4); // Error since params type is string
// Example that results in an error
AddItemsToShoppingBasket("snacks", 2, "burger"); // Error due to type mismatch
AddItemsToShoppingBasket(2, 3, 4); // Error since params type is string
' Example that results in an error
AddItemsToShoppingBasket("snacks", 2, "burger") ' Error due to type mismatch
AddItemsToShoppingBasket(2, 3, 4) ' Error since params type is string
$vbLabelText   $csharpLabel

A syntax error occurs if 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. Only one params argument is permitted in a method parameters declaration. Defining it incorrectly leads to compilation errors.

class Program
{
    static void Main(string[] args)
    {
        // Example 1
        public static void AddItemsToShoppingBasket(double total, params string[] items)
        {
            // Works fine as `params` is the last parameter
        }

        // Example 2, error scenario
        public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total)
        {
            // Error: `params` keyword must be the last parameter 
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Example 1
        public static void AddItemsToShoppingBasket(double total, params string[] items)
        {
            // Works fine as `params` is the last parameter
        }

        // Example 2, error scenario
        public static void AddItemsToShoppingBasket(params string[] items, decimal total, int total)
        {
            // Error: `params` keyword must be the last parameter 
        }
    }
}
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)
'		{
'			' Works fine as `params` is the last parameter
'		}

		' Example 2, error scenario
'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 must be the last parameter 
'		}
	End Sub
End Class
$vbLabelText   $csharpLabel

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.

class Program
{
    static void Main(string[] args)
    {
        public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
        {
            // Compiler Error: Only one params keyword is allowed in the method signature
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        public static void AddItemsToShoppingBasket(params string[] items, params string[] quantity)
        {
            // Compiler Error: Only one params keyword is allowed in the method signature
        }
    }
}
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: Only one params keyword is allowed in the method signature
'		}
	End Sub
End Class
$vbLabelText   $csharpLabel

You Can Pass No Arguments

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

AddItemsToShoppingBasket(); // Works as expected
AddItemsToShoppingBasket(); // Works as expected
AddItemsToShoppingBasket() ' Works as expected
$vbLabelText   $csharpLabel

For any parameter with a params argument, it is considered an optional parameter and can be invoked without passing parameters.

Code Example

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

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

Now add the below code.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        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
        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);
        }
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        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
        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);
        }
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		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
		Console.WriteLine("Enter the cart items as comma separated values")
		Dim itemsString = Console.ReadLine()
		If itemsString IsNot Nothing Then
			Dim items = itemsString.Split(",").ToArray()
			AddItemsToShoppingBasket(items)
		End If
		AddItemsToShoppingBasket("Sample1", "Sample2")

		Console.WriteLine("-------------------------------------------------------")
		Console.WriteLine("Display Cart")

		For Each item In cart
			Console.WriteLine(item)
		Next item
	End Sub
End Class
$vbLabelText   $csharpLabel

Output

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

Introducing IronPDF

IronPDF C# PDF library from Iron Software is 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 excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Installation

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

Install-Package IronPdf

Using IronPDF to Generate a PDF

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

using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;

class Program
{
    public static void Main()
    {
        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 separated 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");
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;

class Program
{
    public static void Main()
    {
        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 separated 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
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports IronPdf

Friend Class Program
	Public Shared Sub Main()
		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 separated 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
$vbLabelText   $csharpLabel

In the above code, we are generating an 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"

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

Conclusion

The params keyword in C# 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.

Frequently Asked Questions

What is the 'params' keyword in C#?

The 'params' keyword in C# allows a method to accept a variable number of arguments, simplifying the syntax for calling methods with varying parameter counts.

How does the 'params' keyword work in a method signature?

In a method signature, the 'params' keyword is used before the parameter type and the parameter name, allowing the method to accept any number of arguments of that type as an array.

Can a method with 'params' accept zero arguments?

Yes, a method with a 'params' parameter can be called without any arguments, as the 'params' parameter is treated as optional.

What are the best practices for using 'params' in C#?

Best practices include placing the 'params' parameter at the end of the parameter list, specifying non-'params' parameters explicitly, and using it judiciously only when the parameter count can vary.

Can a C# method have more than one 'params' parameter?

No, a C# method can only have one 'params' parameter, and it must be the last parameter in the method signature.

What happens if there is a type mismatch with the 'params' parameter?

A syntax error occurs if there is a type mismatch between the arguments passed to the 'params' parameter and the type defined in the method.

How can a C# library be used with the 'params' keyword?

A C# library can be used in conjunction with the 'params' keyword to perform tasks such as generating documents by passing varying content or parameters for dynamic creation.

What is a versatile C# library for document management?

A versatile C# library for document management allows developers to read, write, and manage documents. It may also support conversion between different formats and work across various platforms and operating systems.

How do you install a C# library from NuGet?

A C# library can be installed using the NuGet package manager console with a command such as 'dotnet add package [LibraryName]'.

Is a license required for premium C# libraries?

Yes, premium C# libraries often require a license key for production use. A trial license can usually be obtained from the library's website to test its features.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.