Powershell: [BUG] Custom classes can be redefined in the same scope, via dot-sourcing, take effect in delayed fashion

Created on 28 Jan 2019  路  1Comment  路  Source: PowerShell/PowerShell

If you try to redefine a custom class in the same scope in a script, you get an error that suggests that this is prevented _by design_:

class Foo { [string] $a = 'a' }
# Redefinition: fails with "The member 'Foo' is already defined."
# Note: Does NOT fail if you submit the definitions one by one at the prompt.
class Foo { [string] $b = 'b' } 

However, if "dot-sourcing" is involved, it is possible to bypass this check, in a manner that causes unexpected side effects.

Note that during interactive experimentation you _want_ to be able to redefine classes via dot-sourced scripts:
I often find myself using the following workflow, which currently doesn't work as expected:

# !! [Foo] still has the *previous* definition due to being part of the same script block.
# See repro below.
. <script-with-class-definition-of-Foo>; [Foo]:new()

Steps to reproduce

. { 
  class Foo { [string] $a = 'a' }
  . { class Foo { [string] $b = 'b' } }
  [Foo]::new() | Out-Host
}
[Foo]::new() | Out-Host

Expected behavior

The redefinition of [Foo], given that it effectively happens in the same scope, should be prevented.

Alternatively, the redefinition should predictably take effect _right away_.
This would facilitate the testing scenario mentioned above; not sure if a _warning_ is then called for and, if so, how one would suppress it, if needed.

Actual behavior


a
-
a


b
-
b


That is:

  • The redefinition was quietly accepted, but didn't take effect _inside the block_ being sourced.

  • _After leaving the block_, the redefinition took effect.

Environment data

PowerShell Core v6.2.0-preview.3 on macOS 10.14.2
PowerShell Core v6.2.0-preview.3 on Ubuntu 18.04.1 LTS
PowerShell Core v6.2.0-preview.3 on Microsoft Windows 10 Pro (64-bit; Version 1803, OS Build: 17134.471)
Windows PowerShell v5.1.17134.407 on Microsoft Windows 10 Pro (64-bit; Version 1803, OS Build: 17134.471)
Issue-Bug

Most helpful comment

@mklement0

Note: Does NOT fail if you submit the definitions one by one at the prompt.

An important aspect of how classes work is the "compile unit" i.e. the script text containing the class definition. Each entry at the prompt is its own compile unit which is why you don't see an error when you redefine classes at the prompt.

>All comments

@mklement0

Note: Does NOT fail if you submit the definitions one by one at the prompt.

An important aspect of how classes work is the "compile unit" i.e. the script text containing the class definition. Each entry at the prompt is its own compile unit which is why you don't see an error when you redefine classes at the prompt.

Was this page helpful?
0 / 5 - 0 ratings