C# supply values for all optional parameters

后端 未结 3 1438
南方客
南方客 2021-01-19 21:25

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

3条回答
  •  生来不讨喜
    2021-01-19 22:16

    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");
    

提交回复
热议问题