Alex Rivera | Logout

Default Value in a C# Function

Asked 2011-10-31T10:22:53.610
15

is it possible to do this in C#? (in C++ its not)

function sum ( int a = 9, int b = 4){

}

and then call the function like :

int someValue = sum(, 14) // so 14 is for the second value
c#
Edit
Report

1 Answer

2

Yes this is possible in C# by using named and optional arguments.

public int Sum(int a = 1, int b = 2)
{
    return a + b;
}

Console.WriteLine(Sum(2));    // Writes 4.
Console.WriteLine(Sum());     // Writes 3.
Console.WriteLine(Sum(b: 4)); // Writes 5.

This will result in a being set to 2 and b having it's default value, 2. It will always populate the arguments in order, so if you only pass one argument then only a gets set and the rest will use their default values.

Sum(2)

This will result in a being set to it's default 1 and b being set to it's default 2. As no arguments have been supplied.

Sum()

This will result in a having it's default value 1, and b being set to 4. The reason order of the arguments is ignored in this case is because we're specifying that b should be set to 4 using a named argument.

Sum(b: 4)
answered 2011-10-31T10:26:38.943

Your Answer