So I have a function
public int Sum(var valueA, var valueB, var valueC) {
var summ = valueA + valueB;
return summ;
}
I want to add to summ valueC if it was given. And let user not specify it if he does not want to. How to do such thing?
So I have a function
public int Sum(var valueA, var valueB, var valueC) {
var summ = valueA + valueB;
return summ;
}
I want to add to summ valueC if it was given. And let user not specify it if he does not want to. How to do such thing?
You can do this in C# 4.0 with optional arguments. If you're using a version prior to C# 4.0, you could create an overloaded function that calls your function with a default value.
If you are using .NET 3.5 or earlier you can use Nullable Types.
public int Sum(int valueA, int valueB, int? valueC)
{
int sum = valueA + valueB;
if (valueC.HasValue)
{
sum += valueC.Value;
}
return sum;
}
The calls would be:
int answer1 = Sum(1, 2, 3); // = 6
int answer2 = Sum(1, 2, null); // = 3
Of course the classic way to do this is to use method overloads:
public int Sum(int valueA, int valueB)
{
int sum = valueA + valueB;
return sum;
}
public int Sum(int valueA, int valueB, int valueC)
{
int sum = valueA + valueB + valueC;
return sum;
}
int answer1 = Sum(1, 2);
int answer2 = Sum(1, 2, 3);
If you want to be able to use string
as well as int
either move to .NET4 or create another pair of overloaded methods:
public int Sum(string valueA, string valueB)
{
// Convert the strings to int and call the previous code
// You will need to cope with the case when the strings don't represent numbers
}
public int Sum(string valueA, string valueB, string valueC)
{
...
}
If you want to cope with mixed string
and int
then you'll need even more overloads - which is probably overkill.
In addition to the options that Shane Fulmer provided, you can also use the params keyword to have a function that takes a variable number of parameters:
public int Sum(params int[] values)
{
int sum = 0;
for(int i = 0; i < values.Length; i++){
sum+=values[i];
}
return sum;
}
int answer2Parameters = Sum(1, 5);
int answer3Parameters = Sum(1, 2, 3);
int answer4Parameters = Sum(1, 3, 5, 6);
Of course if you want to limit them to exactly two or three then you probably want to look at optional parameters in C#4.0 or overload the Sum function - by this I mean create two Sum functions, one that takes two parameters and another that takes 3 parameters.
public int Sum(int valueA, int valueB) {
int summ = valueA + valueB;
return summ;
}
public int Sum(int valueA, int valueB, int valueC) {
int summ = valueA + valueB + valueC;
return summ;
}