Related use of C optional parameters

  • 2020-05-10 18:41:49
  • OfStack


static string GetStr(string s = "a", int i = 10, string r = "rrrr")
        {
            return s + i + r;
        }

When called, you can call it in the following ways

             GetStr();
            GetStr("abcde");
            GetStr("abcde", 100);
            GetStr("abcde", 100, "hjklmn");

Also, the order of the parameters can't be changed, you can't skip one parameter and use the following parameter type, so there's a problem here, what if I want to call this method and I only want to use the first and the third parameter.

In fact, on the call of optional parameters, Microsoft introduced a named parameter, namely

GetStr (s: "abcde r:" hijklmn "); Just mark down the parameter name. (named parameters can only be the name of the original method followed by a colon ":")

In this way, later reloading can save a lot of things. Eliminating large sections of code overload methods


Related articles: