Calling a Method with Multiple Defaults

I was interested because I have a method with several default parameters

private string reqLabel(string label, byte fontSize = 10, string fontColour = "#000000", string fontFamily = "Verdana"  )
{
   return "<br /><strong><span style=\"font-family: " + fontFamily + ",sans-serif; font-size:" +fontSize.ToString() + "px; color:"+ fontColour + "; \">" + label +" : </span></strong>";
}

and when I call the method, I have to do this to

reqLabel("prerequitie(s)")
reqLabel("prerequitie(s)", 12) 
reqLabel("prerequitie(s)", 12 , "blue")
reqLabel("prerequitie(s)", 12 , "blue", "Tahoma")

so my question is: is there a way to skip the first few parameters by default?

Let's say I want to introduce only the color and font family as follows:

reqLabel("Prerequisite(s)" , "blue" , "Tahoma") 

/* or the same with 2 comma where the size param is supposed to be. */

reqLabel("Prerequisite(s)" ,  , "blue" , "Tahoma") 
+4
source share
3 answers

Yes, this is possible with an explicit name:

reqLabel("Prerequisite(s)" , fontColour: "blue", fontFamily: "Tahoma")

Just remember that named arguments should always be the last - you cannot specify positional arguments after the name. In other words, this is not allowed:

reqLabel("Prerequisite(s)" , fontColour: "blue", "Tahoma")
+9
source

Use named arguments

reqLabel("prerequitie(s)", fontSize: 11)
+3

:

reqLabel("Prerequisite(s)" , fontColour: "blue" , fontFamily: "Tahoma") 
+2

Source: https://habr.com/ru/post/1527731/


All Articles