Today in writing code, suddenly think of a situation can be applied to the default parameters of the case, is someone else to write the method (has been used in many places, you now want to add a parameter, and do not have to change the original reference code). Of course you can write a method of overloading, I have also wanted to write a reload to add this parameter condition. Because the overloads are already used, we have learned the default conditions of the method parameters.
I also looked at the garden inside the old a wrote the article, speak very well. But what I have said, can be used as a primer, but not as a guideline.
There is nothing wrong with this notation, but if the method is called from outside the module, changing the default value of the parameter is potentially dangerous, and call site embeds the default value in the invocation, if you later change the default value of the parameter, but do not recompile the code inside the calling site, It will still pass the old default value when calling your method, so consider using 0/null as the Sentinel value to indicate the default behavior, so that even if you change the default value, you do not have to recompile all the code that contains the call site.
The first approachStatic voidTestMethod (stringFoostringBar="bar123") {Console.WriteLine ($"{Foo}{bar}"); }
The second approachStatic voidTestdefaultmethod (stringFoostringBar =NULL) {Bar= bar??"bar123"; Console.WriteLine ($"{Foo}{bar}"); }
It is recommended to use the following procedure
This above is the most important, if you want to use the default parameters and function overload, depending on the situation to be determined.
In C #, once a default value has been assigned to a parameter, the compiler will apply a custom attribute to the internal parameter (OptionalAttribute), which will store the metadata type persistence of the final produced file, in addition to that, the attribute The compiler will apply a defaultparametervalueattribue to the parameter, and it will store this feature persistence in the metadata of the final file.
Default parameters inside the C # method