Skip to content

Operator Overloading with Script Methods #26078

@StartAutomating

Description

@StartAutomating

Summary of the new feature / enhancement

The recent string of issues makes me wish for a more generalized feature.

Many .NET classes do not support operator overloading, but could be extensibly overridden in PowerShell.

Since PowerShell has an extended type system, we can effective add a static script method to any class.

I propose that PowerShell should check for a ScriptMethod overload when a compiled operator is not found, and use this instead.

This would open up an incredibly large number of doors for PowerShell, as overloading operators is currently impossible in pure PowerShell.

Proposed technical implementation details (optional)

Let's imagine we wanted to make a PSObject that could add.

Either approach should theoretically work, though using Update-TypeData is more likely to be quick

$foo = [PSCustomObject]@{PSTypeName='foo';Value=42} |
   Add-Member ScriptMethod 'operator +' {$this.Value += $args} -PassThru

$foo + 1
$foo.Value # Should be 43
Update-TypeData -TypeName Foo -MemberName 'operator +' -MemberType ScriptMethod -Value {
    $this.Value += $args
} 
$foo = [PSCustomObject]@{PSTypeName='foo';Value=42}
$foo + 1
$foo.Value # Should be 43

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugWG-Enginecore PowerShell engine, interpreter, and runtimeWG-ReviewedA Working Group has reviewed this and made a recommendation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions