This is the first blog from a series of blog post which I'm planning to do on whet's new in Visual C #4.0
This is the first article in the series of Visual C #4.0 new features I plan to write.
Optional parameter (optional parameters)
Optional parameters is a new feature in C #4.0 which will let you set a default value for an argument of a method. in case that the collie of the method will omit the argument the default value will take its place.
The optional parameter (optional parameters) is a new feature of C #4.0. You can set a default value for the parameter of a method. (Note: Set a default value for a parameter, which is an optional parameter) if the called method ignores the optional parameter, it will be replaced by the default value.
So instead of writing the following code:
Therefore, replace the following code:
Code
1 class Program
2 {
3 static void main (string [] ARGs)
4 {
5 saysomething ();
6 saysomething ("ohad ");
7
8 console. Readline ();
9}
10
11 public static void saysomething ()
12 {
13 console. writeline ("Hi! ");
14}
15
16 public static void saysomething (string name)
17 {
18 console. writeline (string. Format ("Hi {0 }! ", Name ));
19}
20}
21
You will only have to write:
You only need to write as follows:
Code
1 class Program
2 {
3 static void main (string [] ARGs)
4 {
5 saysomething (); // (Translator's note: equivalent to saysomething ("");)
6 saysomething ("ohad ");
7
8 console. Readline ();
9}
10
11 public static void saysomething (string name = "")
12 {
13 console. writeline (string. Format ("Hi {0 }! ", Name ));
14}
15}
16
The statementName = ""At Line 11 does the trick of the optional parameter with passing and empty string as the optional parameter.
11th rowsName = ""Is an optional parameter. The function is to pass an empty string as the selection parameter.
Note that some of the reader of this post my think that its better to use string. Empty instead of double quote "" as it normally do:
Note that some readers who read this article think that using string. Empty is better than using double quotation marks. However:
Code
1 class Program
2 {
3 static void main (string [] ARGs)
4 {
5 saysomething ();
6 saysomething ("ohad ");
7
8 console. Readline ();
9}
10
11 public static void saysomething (string name = string. Empty)
12 {
13 console. writeline (string. Format ("Hi {0 }! ", Name ));
14}
15}
16
Using string. Empty will result with a compilation error:
Using string. Empty will cause a compilation error:
"Default parameter value for 'name' must be a compile-time constant"
"The default value of 'name' should be a compilation constant"
And as it string. Empty is not a literal.
String. Empty is not a literal value.