Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a method with multiple default values

Tags:

methods

c#

i was wondering, because i have a method with multiple 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 it i have to do it in order

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

so my question is, is there any way to skip the first few default parameters?

Let's say i want to input only the colour, and the font-family like this:

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

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

reqLabel("Prerequisite(s)" ,  , "blue" , "Tahoma") 
like image 801
173901 Avatar asked Feb 19 '14 15:02

173901


People also ask

How do you pass a default argument in Java?

There are several ways to simulate default parameters in Java: Method overloading. void foo(String a, Integer b) { //... } void foo(String a) { foo(a, 0); // here, 0 is a default value for b } foo("a", 2); foo("a");

Does Java allow default values to arguments?

Short answer: No. Fortunately, you can simulate them. Many programming languages like C++ or modern JavaScript have a simple option to call a function without providing values for its arguments.

Do I always have to add parameters to every function?

Parameters are essential to functions, because otherwise you can't give the function-machine an input.

Why will you use default parameters?

Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value. A default parameter can be anything from a number to another function.


2 Answers

Yes, it is possible with explicit naming:

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

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

reqLabel("Prerequisite(s)" , fontColour: "blue", "Tahoma")
like image 180
Andrei Avatar answered Oct 14 '22 23:10

Andrei


Use named arguments

reqLabel("prerequitie(s)", fontSize: 11)
like image 27
Alberto Avatar answered Oct 14 '22 23:10

Alberto