Skip to content

For validation-constrained function parameters, prevent invalid default values. #8795

@mklement0

Description

@mklement0

Summary of the new feature/enhancement

I would be helpful if an error occurred at parse time if a script / function parameter default value were encountered that contradicts the parameter's validation attributes.
(Omitting a default value should always pass the check, however).

This would prevent self-contradictory definitions such as the following, which could easily happen in the course of refactoring, for instance:

function foo {
    [ValidateSet('one', 'two')]
    $bar = 'uno'   # Invalid, because it contradicts the validation set.
}

Currently, the above is quietly accepted, which means that you cannot rely on the parameter variable to have a valid (non-null) value.

Caveats:

  • Technically, that would be a breaking change, as it is conceivable that there are functions out there that exploit this permissiveness deliberately in order to use an invalid values as an explicit signal that no argument was passed, along the lines of: . { param([ValidateSet("one", "two")] $foo="<none>") $foo }.
    That said, there was never a good reason for this technique (use $PSBoundParameters.ContainsKey() to see if a value was passed), so it is hopefully a Bucket 3: Unlikely Grey Area change.

  • Also, as @iSazonov points out below, this change may be problematic from a performance perspective.

Proposed technical implementation details (optional)

Bug #8778 suggests that code to enforce this check already exists, but (a) it currently only surfaces via Invoke-Expression and (b) is currently overzealous in that it also considers the absence of a default value invalid.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugNeeds-TriageThe issue is new and needs to be triaged by a work group.Resolution-No ActivityIssue has had no activity for 6 months or moreWG-Languageparser, language semantics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions