6

I need $this to work inside static class! How to achieve that? Any workaround? I have analyzed return of Get-PSCallStack in class context and found nothing useful.

I need this for (a) logging and for (b) calling other static methods of same class without mentioning its name again and again.

Sample code (PowerShell v5):

class foo {
    static [void]DoSomething() {
        [foo]::DoAnything()  #works

        #$this.DoAnything   #not working

        $static_this = [foo]
        $static_this::DoAnything() #works

    }
    static [void]DoAnything() {
        echo "Done"
    }
}

[foo]::DoSomething()
Anton Krouglov
  • 3,077
  • 2
  • 29
  • 50
  • Typo: _not available_ – Anton Krouglov Aug 22 '16 at 22:45
  • 2
    This is technically a duplicate of this question: http://stackoverflow.com/questions/2113069/c-sharp-getting-its-own-class-name. It's as messy to do what you ask (for static methods) in C# as it is in PowerShell. – Chris Dent Aug 23 '16 at 07:52
  • @Chris Dent : `[System.Reflection.MethodBase]::GetCurrentMethod().DeclaringType` does not seem to work. Attributes of `GetCurrentMethod()` result indicate that method is dynamic. Anyway in C# you can call DoAnything from DoSomething without full reference that is `static void DoSomething() { DoAnything(); }`. Exactly this I am missing in PowerShell. – Anton Krouglov Aug 23 '16 at 08:55
  • Fair point, but I doubt you'll get a way neater than `[foo]::DoAnything()` because single-label statements are executed as function calls first. That and about the only apparent method available for getting the type (GetCurrentMethod()) doesn't hold a type. The same problem exists when referencing fields on a PS class (the $this variable must be used). – Chris Dent Aug 23 '16 at 09:09

1 Answers1

1

Static classes do not have this pointer. See MSDN

Static member functions, because they exist at the class level and not as part of an object, do not have a this pointer. It is an error to refer to this in a static method.

You must call method by class name.

Paweł Dyl
  • 8,888
  • 1
  • 11
  • 27
  • 1
    Thank you for prompt response Pawel, but apparently your suggestion does not solve the problem. As I have indicated in my question there is at least one workaround `$static_this = [foo]`. Just looking for better one. – Anton Krouglov Aug 20 '16 at 19:27