How do I add optional parameters to methods?
Can optional parameters be declared in methods?
In delphi, for example, I can do something like:
procedure Test(p1:integer;p2:integer;p3:integer = 2;p4:integer = 4)
When I call this function, I can call it with four parameters or two parameters:
Test(2,3); //p3 = 2,p4 = 4.
Test(2,3,4,5); //p3 = 4,p4 = 5;
How is this possible in C #?
source to share
I'm afraid this is not possible in C # 1 through 3. However, the good news is that since it was a very much requested feature (although there are certainly some who would rather not see it), Microsoft finally decided to add its in C # 4.
The C # 4 syntax looks like this:
public static void SayHello(string s = "Hello World!")
{
Console.WriteLine(s);
}
Using:
SayHello(); // Prints "Hello World!"
SayHello("Hello."); // Prints "Hello."
SayHello(s: "Hello."); // Prints "Hello."
(The last example uses a named argument, which isn't really needed in this case, but helps when you have multiple optional parameters.)
You can read more about this issue in this blog post .
source to share
You cannot do this yet. I think this is a C # 4.0 feature .
You can use params as a job, but that can only be used sequentially and not in the way some languages ββconsider default parameters.
source to share
You are using overloads like this
Test(int p1, int p2)
Test(int p1, int p2, int p3)
You can make them call a private method like this
Test(int[] ps)
and then process the data.
Another way to deal with this is to NOT use overloads / optional parameters and instead name the methods according to what they are supposed to do - this might seem like a bad trade-off, but your code will probably be easier to read.
source to share