I\'m reading a book for C# and I\'m in the chapter of named and optional parameters. I\'ve read a bullet where it says:
\"If multiple optional paramet
Take this method signature for example:
public void MyMethod(object arg1, string arg2 = null, int? arg3 = null, MyType arg4 = null)
{
// do stuff
}
You cannot call this method and only provide values for arg1
and arg3
, like:
MyMethod(obj, 5);
You have to fill the arguments in between as well. The reason for this is that the compiler does not know you meant the third argument. So it will actually try to put the value in the first optional parameter, being a string
. The third parameter is not a string but a nullable int
, so you get a compilation error.
However, since C# 4, you can also do:
MyMethod(obj, arg3: 5);
These are called named parameters. See this MSDN article for more information about that. In this case, the compiler can still ensure type-safety because it knows the which parameter you are supplying the value for.
edit: as others pointed out, the order of the arguments in the declaration of the method is also important. All optional parameters must be at the end. That is however not what the question is actually asking. The question states 'specifying values', and you do that when calling the method.
It simply means that optional parameters must all be last in the parameter list.
public void Method(int param1, int param2 = 0, int param3 = 0)
{
//This works
}
versus
public void Method(int param1 = 0, int param2 = 0, int param3) //Param3 isn't optional.
{
//This does not!
}
public void Method(int param1 = 0, int param2, int param3 = 0) //Param2 isn't optional.
{
//Neither does this!
}
It means you cannot have normal parameters in between or after 2 or more optional parameter
void MyMethod(int param1, int param2, int optparam3 = 5, int param4)
my example shown is not valid (following what the statement illustrate), the optional parameters MUST ALWAYS be the last ones.
Secondly You question might mean that if multiple optional parameter exist for a method, you must provide all of them if you decide to provide 1. This statement is also false as of .net4.0. I cannot tell for older .net version as i nearly never use optional but if you have 3 optional parameters you CAN only set the second one if you want.
They mean if you want only optional #2 you have to fill optional #1 and optional #3 which is not true. You can in the call of the method specify one or many optional using the following format and jump any parameter you don't want :
MyMethods(param1,param2,optional6 : 225, optional9 : "a string");