TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Params Method

This C# tutorial uses the params keyword. Params allows a variable number of arguments.

Params enables methods to receive variable numbers of parameters.

With params, the arguments passed to a method are changed by the compiler to elements in a temporary array. This array is then used in the receiving method.

Example. To begin, we see a program that uses the params keyword that accepts any number of integer values. That method internally sums the values of those integers and returns that value.

IntReturn

Keyword: The params keyword is specified before the array type declaration in a parameter list in a method.

Tip: You can use the params keyword on instance or static methods. It must be the last argument in the parameter list.

Static Method

C# program that uses params keyword

using System;

class Program
{
    static void Main()
    {
	// Call params method with one to four int arguments.
	int sum1 = SumParameters(1);
	int sum2 = SumParameters(1, 2);
	int sum3 = SumParameters(3, 3, 3);
	int sum4 = SumParameters(2, 2, 2, 2);

	// ... Write results of the method invocations.
	Console.WriteLine(sum1);
	Console.WriteLine(sum2);
	Console.WriteLine(sum3);
	Console.WriteLine(sum4);
    }

    static int SumParameters(params int[] values)
    {
	// Loop through and sum the integers in the array.
	int total = 0;
	foreach (int value in values)
	{
	    total += value;
	}
	return total;
    }
}

Output

1
3
9
8

The SumParameters method is called with 1-4 arguments. All of these method calls go into the SumParameters method defined next in the program. The SumParameters method acts on these parameters and returns an integer value.

Then: These result values are printed to the screen with the Console.WriteLine method.

Console.WriteLine

And: The params keyword is placed in the parameter list of the method signature of SumParameters above.

You can only have a params argument at the end of a declaration list. You cannot have regular parameters following the params argument with commas in the parameter list of a method signature.

Implementation. Let's examine how the C# compiler interprets and writes the intermediate language for params methods. When a params method call is encountered, the parameters are put into a new array of the matching type.

In each case where SumParameters is found, a new int array of various lengths is allocated on the managed heap. Because the integers are value types, their values are copied into this array.

Int Array

Disassembled code inside Main method: C#

private static void Main()
{
    int num = SumParameters(new int[] { 1 });
    int num2 = SumParameters(new int[] { 1, 2 });
    int num3 = SumParameters(new int[] { 3, 3, 3 });
    int num4 = SumParameters(new int[] { 2, 2, 2, 2 });
    Console.WriteLine(num);
    Console.WriteLine(num2);
    Console.WriteLine(num3);
    Console.WriteLine(num4);
}

Creating an array with a new array creation expression takes time. This is normally slower than pushing parameters onto the evaluation stack. For this reason, performance-critical methods are not best implemented with params keywords.

We do not include a benchmark for params methods such as this one. This is because the params keyword results in more intermediate language instructions and allocations, making it obviously slower than regular method invocations.

Note: Normal methods use the evaluation stack, not the managed heap, for invocations. They are considerably faster.

Activation Record

Discussion. The params keyword is most useful when designing a library for other programmers to widely use. If you have complete control over all usages of the method, you may not need params because you can simply add the necessary overloads.

Note: The best examples of params methods include the string.Concat method and the string.Format method.

string.Concatstring.Format

We reference the book ".NET Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries." It suggests that for performance, you provide common overloads that avoid the params keyword on some methods.

Consider providing special overloads and code paths for calls with a small number of arguments in extremely performance-sensitive APIs. This makes it possible to avoid creating array objects.

Framework Design Guidelines

Alternatives. As mentioned, there are alternatives to using params. These alternatives will impact performance much less. You could use a set of overloads instead of params. You could just require an array parameter.

OverloadArrays

Also: You could use optional parameters. With these you can omit arguments if you just want the default value.

Optional Parameters

Summary. Params is used to describe methods that have flexible parameter counts. It is placed in the final position in the parameter list of methods. It will often reduce performance of method invocations.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf