Skip to content

Give classes a Clone() method #24139

@jazzdelightsme

Description

@jazzdelightsme

Summary of the new feature / enhancement

Sometimes one must make a copy of an object, such as to avoid reference cycles. If the object supports ICloneable, then you can just .Clone() it, and you're good.

But PowerShell classes do not implement ICloneable.

Searching how to make a copy of an object in PowerShell yields a bunch of results, usually including lots of ways to serialize an object to a string and then deserialize it (using e.g. ConvertTo-Json+ConvertFrom-Json, or the PSSerializer type) or other tricks like using Select-Object. Those approaches have significant downsides: they are relatively inefficient, and leave you with a different object type (PSCustomObject or PSObject). Plus they "look weird": when you see code like that, it's not obvious why in the world someone would e.g. want to round-trip an object through a string, just for fun.

Thus it would be great if we could just have a .Clone() method on instances of our PowerShell classes.

(Some people may have manually given their class a .Clone() method: the implementation would need to be careful to let an explicitly provided implementation win.)

Proposed technical implementation details (optional)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugResolution-AnsweredThe question is answered.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions