#586 – Default Values for Optional Parameters Must Be Constants

When you specify a default value for an optional parameter, that value must be a constant, of the same type as the parameter.  The expression must be able to be evaluted at compile-time.  The parameter’s default value can be one of the following:

  • A constant expression (see below)
  • new S(),  where S is a value-type (parameters not allowed on constructor)

A constant expression is one that can be fully determined at compile-time.  In other words, you can use any expression that you’d use in the initialization of a constant.

For reference types, the expression must be null, with the exception of the string type.

        private const int OFFSET = 1;

        static void Optional1(int x = 5 + OFFSET, double y = 1.0/3.0) { }
        static void Optional2(Point3D fln = new Point3D()) { }
        static void Optional3(Dog d = null) { }
        static void Optional4(string s = "DEFAULT") { }

        static void Main()
        {
            Optional1();
            Optional2();
            Optional3();
        }
Advertisement