Its was 2004, when I was started to study Pascal lang. I was a better code writer (remember, those days, we write code first on a book, then we re-write on a MS-DOS machine and compile it) and one day our instructor asked us to write a program to calculate average marks of the students. He didn’t mention, for how many students we are going to calculate the average. I don’t know how other wrote the code, though in that class only 3 were regular attendees, we never look in to others books, we thought it as a very very bad habit. So I write a for loop (I am in love with “for loop” since 2004 and “foreach” since 2011) that iterates some x times (say 10 times, I forgot the exact number that I used) and asked for marks and add it to a predefined variable and then divide the sum with x and print the answer. This was praised by instructor. I was a very beginner to programming and this approach was an excellent one for people like that. This might be the same way how you also have done when your early programming ages.
Now, suppose if someone comes to you and ask to do the same program for un-known number of people, you might use some data structures (List, Stacks, LinkedLists) to make this happen. But you know there is a better, memory saving approach to this. Thats what we call as Variable Parameters. This is a classic concept for most people don’t use this these days in favor of data structures. This is a kind of
polymorphism but still really efficient.
A simple example for this in C# might be
Just look at the method
avg, that has been implemented with
params keyword with
int this means, this tells that the method has the ability to take variable number of arguments with same data type (here
But be careful when you define a param method and be sure to make the param parameter is coming as the very last parameter
Some extra tips
Comparing to regular method invocations params methods are slower, while they are really 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.