powershelloopoverridingbase-class

Powershell Call Base Class Function From Overidden Function


I want to make a call to the parent function from its overidden function, i isolated my problem in the following code:

class SomeClass{
  [type]GetType(){
    write-host 'hooked'
    return $BaseClass.GetType() # how do i call the BaseClass GetType function??
  }
}
SomeClass::new().GetType()

i am expecting an output like this:

hooked
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     SomeClass                                System.Object

Solution

  • In oder to call a method on the base class, cast $this to it (([object] $this).GetType(), in your case, given that your class implicitly derives from [object](System.Object)):

    class SomeClass  {
      [type]GetType(){
        Write-Verbose -Verbose hooked!
        # Casting to [object] calls the original .GetType() method.
        return ([object] $this).GetType()
      }
    }
    
    [SomeClass]::new().GetType()
    

    As an aside re referring to the base class in PowerShell custom classes: