-1

How to using params keyword with [Optional]?
i want to use both keywords params and Optional but it raise error

public void m( int x,[Optional] int c,params string [] arr)
{
    Console.WriteLine("x= {0}", x);        
    foreach (string item in arr)
    {
        Console.WriteLine("name ={0}\n",item);
    }
    public static void Main(){
    Program x = new Program();
    x.m(10,"mido","sfs","sgsd"); // here error why?
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • What is the error you are getting ? – Pratyay Aug 11 '17 at 13:04
  • 1
    When you call the method, you cannot choose not to give an argument for the optional parameter (`c`) and yet provide an argument for the parameter that follows. – Yacoub Massad Aug 11 '17 at 13:04
  • A better solution would be to use two methods, one with the optional parameter (which will then not be optional) and one without – DirtyNative Aug 11 '17 at 13:05
  • Also a possible solution would be to mark the optional parameter only as Nullable. Then you could check that value inside your code – DirtyNative Aug 11 '17 at 13:07
  • You have your main-method defined in your `m`-method. This however doesn´t have anything to do with your actual problem, however you shpuld strife towards verifyable examples. – MakePeaceGreatAgain Aug 11 '17 at 13:10
  • 1
    Basically `params` has to be at the end, and optional cannot be followed by something that isn't optional, otherwise there could be ambiguity. Based on those rules you cannot use them together. Instead just create multiple overloads. – juharr Aug 11 '17 at 13:10

1 Answers1

0

I'm not so sure about that keyword, however if you're passing optional arguments to your class, you need to set the default values. Also, it's key to remember that optional parameters cannot be followed by non-optional parameters. In your example your optional param is followed by a non optional string array.

An example:

public void ExampleMethod(int required, string optionalstr = "default string",
    int optionalint = 10)

Read more: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments

Capn Jack
  • 1,201
  • 11
  • 28
  • Optional parameters cannot be followed by non-optional parameters that's the issue here. – juharr Aug 11 '17 at 13:09
  • @juharr My example contains 3 arguments in the order of required, optional, and optional. Look it over again. It's not even my example. that's straight from MSDN. – Capn Jack Aug 11 '17 at 13:10
  • Your example is fine, but note that the OP has a non-optional parameter following an optional one. – juharr Aug 11 '17 at 13:11
  • @juharr Oh okay good point. Your initial wording was quite confusing. I've added that to my answer now. – Capn Jack Aug 11 '17 at 13:11