Skip to main content

C# Snippet Tutorial - The Params Keyword [Beginner]


We are going to take a quick look at another C# keyword today - the params keyword. This keyword is another one of those not well known keywords in C#, but it makes life a lot easier in certain situations - and code a lot cleaner. What does the params keyword do, you ask? Well, lets take a look.

The main use of the params keyword is to give the ability to create functions that take a variable number of arguments - often called "variadic" or "variable arity" functions. This is not a feature specific to C#, and C# is definitely not the first - although it is easier in some languages than others. C and C++ have it, in the form of the "..." syntax, and Java uses that syntax as well. Everything from scheme to javascript can do it - although as you get toward javascript the syntax becomes somewhat ugly (perhaps that is a topic for another tutorial).

But this is a tutorial about C#, not about those other languages. So here is some code:
public int Add(params int[] list)
{
  int sum = 0;
  foreach (int i in list)
    sum += i;
  return sum;
}
 
So, as you can see, you use the params keyword in the argument list. Essentially, what that argument block is saying is that it can take an arbitrary number of ints, and those ints will be presented to the internals of the function as an array of ints.

Here are some ways that you can call this function:
int ans1 = Add(1);

int ans2 = Add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

int ans3 = Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });

int ans4 = Add();
 
And here are the values those result variables will hold:
ans1: 1
ans2: 55
ans3: 55
ans4: 0
 
So as you can see, you can call this Add function with 0 or more arguments, and you can even pass in an array (and that array gets passed straight through). While you can pass in arrays where there is a param argument, you cannot mix and match arrays and regular values at all:
int ans5 = Add(new int[] { 1, 2, 3, 4, 5}, 5, 6, 7, 8);
// Error: The best overloaded method match for 'Add(params int[])'
// has some invalid arguments

int ans6 = Add(5, 6, 7, 8, new int[] { 1, 2, 3, 4, 5 });
// Error: The best overloaded method match for 'Add(params int[])'
// has some invalid arguments
 
Another thing to note is that the params argument does not need to be the only argument to the function, but it does need to be the last. For instance, this is valid:
public void AddAndPrint(string str, params int[] list)
{
  int sum = 0;
  foreach (int i in list)
    sum += i;
  Console.WriteLine(str + sum);
}
 
But this is not valid at all:
public void AddAndPrint(params int[] list, string str)
{
  int sum = 0;
  foreach (int i in list)
    sum += i;
  Console.WriteLine(str + sum);
}

// Error: A params parameter must be the last parameter in a formal parameter list  

You can do some cool things with the params keyword. For instance, here is an integer "fold" method:
public delegate int FoldIntDelegate(int a, int b);

public static int Fold(FoldIntDelegate fid, params int[] list)
{
  int result = 1;
  foreach (int i in list)
    result = fid(result, i);
  return result;
}
 
And you can call it like this:
int ans7 = Fold(new FoldIntDelegate(delegate(int a, int b) { return a * b; }), 
                1, 3, 5, 7, 9));
 
So here we are passing in an anonymous delegate that will perform the multiplication of 2 ints and return the result, and the Fold method takes that delegate and 'folds' it over the variable number of integer arguments, giving a cumulative multiplication total, in this case resulting in the answer 945.
Well, that is it for the params keyword in C#. Thanks for reading.

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >(); ...

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as...

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV...