Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# supply values for all optional parameters

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 parameters exist and a value is specified for one, all preceding optional parameters must also be supplied values"

Can you please give me an example because I'm not able to reproduce the above statement from code.

like image 852
Charalambos Avatar asked Dec 01 '22 00:12

Charalambos


1 Answers

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.

like image 89
pyrocumulus Avatar answered Dec 13 '22 17:12

pyrocumulus