#585 – Optional Parameters Must Come Last

If you define a method that includes optional parameters, they must come after any required parameters.  This means that your options for required vs. optional parameters are:

  • No parameters at all
  • 1 or more required parameters (no default values)
  • 1 or more optional parameters (with default values)
  • 1 or more required parameters, followed by 1 or more optional parameters
        static void NoParams() { }
        static void RequiredOnly(int x, int y) { }
        static void OptionalOnly(int x = 5, int y = 10) { }
        static void RequiredAndOptional(int x, int y, int a = 1, int b = 2) { }

        static void Main()
        {
            NoParams();
            RequiredOnly(5, 10);

            OptionalOnly();
            OptionalOnly(1);
            OptionalOnly(1, 2);

            RequiredAndOptional(1, 1);
            RequiredAndOptional(1, 2, 3);
            RequiredAndOptional(1, 2, 3, 4);
        }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: