TheDeveloperBlog.com

Home | Contact Us

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

<< Back to C-SHARP

C# params Keyword

Use the params keyword for varargs methods. Params allows a variable number of arguments.
Params. This keyword enables methods to receive variable numbers of parameters. The arguments passed to a method are changed (by the compiler) to elements in a temporary array.KeywordsOptional ParametersOverload
Params, array. The arguments array is then used in the receiving method. This impacts performance. But it can make your code look clean and elegant.
To begin, we use the params keyword on a method that accepts integer values. That method internally sums the values of those integers and returns that value.

Params: 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.

SumParameters: This is a varargs method—it accepts a variable number of arguments.

Arguments: SumParameters is called with 1-4 arguments. It acts on these parameters and returns an integer value.

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
Implementation. Let's examine how the C# compiler handles params methods. When a params method call is encountered, the parameters are put into a new array.

Note: In each case where SumParameters is found, a new int array of various lengths is allocated on the managed heap.

And: 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); }
Benchmark. Creating an array is slower than pushing parameters onto the evaluation stack. Performance-critical methods are not best implemented with params keywords.

Version 1: This version of the method uses the params keyword in its formal parameter list.

Version 2: This version uses 3 int arguments. It has less capability than GetProduct() but also avoids an entire array on each call.

Result: Avoiding params is many times faster for this example. For numeric code, using params is a bad choice.

C# program that benchmarks params using System; using System.Diagnostics; using System.Runtime.CompilerServices; class Program { static int GetProduct(params int[] values) { // Use params. int result = 1; foreach (int value in values) { result *= value; } return result; } static int GetProduct2(int value1, int value2, int value3) { return 1 * value1 * value2 * value3; } const int _max = 1000000; static void Main() { // Version 1: use params method. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { GetProduct(2, 2, 3); } s1.Stop(); // Version 2: use int arguments. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { GetProduct2(2, 2, 3); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 9.11 ns params 0.27 ns int, int, int
A discussion. The params keyword is most useful when designing a library. 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 adding overloads to avoid the params keyword.

Quote: 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).

A 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


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