To explain the question on a simple example, let's say:
I have a method which takes the average of two numbers:
private double TakeAverage(double n1,double n2)
{
average = (number1 + number2) / 2.0000;
return average;
}
And I call it like:
textBox3.Text = (TakeAverage(number1, number2)).ToString();
Q1:
How to make this function able to run without calling it multiple times like:
TakeAverage(number1, number2, number3, number4, number5) // as wanted number of times...
Q2:how to make this function changing return value by number of values which it takes?
For example
Substring(1) //if it takes just one value, it returns all the chars after first char but
Substring(1,2)//if it takes two values, it returns 2 characters after first char
Check this out:
public double TakeAverage(params double[] numbers)
{
double result = 0.0;
if (numbers != null && numbers.Length > 0)
result = numbers.Average();
return result;
}
As params
allows the client to send nothing, we should test whether numbers
exists and has items.
Usage:
double average = TakeAverage(1, 2, 3, 4.4); //2.6
double anotherAverage = TakeAverage(); //0
double yetAnotherAverage = TakeAverage(null); //0
UPDATE
Based on your comments, I understand that you're looking for something that's called overload: you want that a given method behaves differently based on its arguments.
I'll give an example, you must modify it to suit your needs.
Let's pretend that, besides our original TakeAverage
method, we want another one that does an average and multiplies it for a given number. It would be something like:
public double TakeAverage(int factor, params double[] numbers)
{
double result = 0.0;
if (numbers != null && numbers.Length > 0)
result = numbers.Average() * factor;
return result;
}
Usage:
double average = TakeAverage(1.0, 2, 3, 4.4); //2.6
double notAnAverage = TakeAverage(1, 2, 3, 4.4); //3.1333...
Note that I had to explicitly say that the first number is a double
(1.0
), otherwise it would fall on the second overload and multiply it.