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 #?

0


source to share


7 replies


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 .

+5


source


You will have to either wait for C # 4.0 , which supports optional parameters, or uses standard overloading mechanisms:



void Test(int p1, int p2, int p3, int p4)
{ }

void Test(int p1, int p2)
{
    Test(p1, p2, 2, 4);
}

      

+4


source


This is possible in C # 4.0, but until it's released, you can get 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);
}

      

+4


source


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...

}

      

+1


source


using System;
using System.Runtime.InteropServices;

   public static void SayHello([Optional][DefaultParameterValue("Hello Universe!")] string s)
   {
      Console.WriteLine(s);
   }

      

Done! :)

+1


source


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.

0


source


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.

0


source







All Articles