Reputation: 35502
Is it possible to declarate optional parameters 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 that function I can call it with four parameters or with two parameters:
Test(2,3); //p3 = 2,p4 = 4.
Test(2,3,4,5); //p3 = 4,p4 = 5;
How is that possible in C#?
Upvotes: 0
Views: 588
Reputation: 147270
I'm afraid this isn't possible in C# 1 to 3. However, the good news is that because it's been a much-demanded feature (though there are certainly some who would rather not see it), Microsoft have finally decided to add it to C# 4.
The C# 4 syntax goes as follows:
public static void SayHello(string s = "Hello World!")
{
Console.WriteLine(s);
}
Usage:
SayHello(); // Prints "Hello World!"
SayHello("Hello."); // Prints "Hello."
SayHello(s: "Hello."); // Prints "Hello."
(The last example uses a named argument, which really isn't necessary in this case, but helps when you have multiple optional parameters.)
You can read more about that subject on this blog post.
Upvotes: 5
Reputation: 35502
using System;
using System.Runtime.InteropServices;
public static void SayHello([Optional][DefaultParameterValue("Hello Universe!")] string s)
{
Console.WriteLine(s);
}
Done! :)
Upvotes: 1
Reputation: 56934
It will be possible in C# 4.0, but, untill that gets released, you can work around it by creating overloaded versions of your method:
public void MyMethod( int a, int b, int c )
{
...
}
public void MyMethod( int a, int b)
{
MyMethod(a, b, 4);
}
Upvotes: 4
Reputation: 1610
You can use variable arguments
Use the params keyword.
void paramsExample(params int[] argsRest)
{
if(argsRest.Length == 2) then...
else if(argsRest.Length == 4) then...
else error...
}
Upvotes: 1
Reputation: 15196
You use overloads like this
Test(int p1, int p2)
Test(int p1, int p2, int p3)
You can have them call a private method like this
Test(int[] ps)
and then process the data.
Another way to handle this is to NOT use overloads/optional parameters, and instead name the methods according to what they are ment to do - it might seem like a bad tradeoff, but your code will probably get easier to read.
Upvotes: 0
Reputation: 115721
You'll either have to wait for C# 4.0, which supports optional parameters, or use standard overloading mechanisms:
void Test(int p1, int p2, int p3, int p4)
{ }
void Test(int p1, int p2)
{
Test(p1, p2, 2, 4);
}
Upvotes: 4
Reputation: 5511
You can't do that yet. I think it's a feature of C# 4.0.
You can use params as a work around, but that can only be used sequentially, not the way some languages treat default parameters.
Upvotes: 0