r/PowerShell • u/xXFl1ppyXx • 7d ago
Question Methods of a class that's not instanced
Hi there,
i can't seem to find relevant informations for this particular topic using my own google skills so maybe someone here can shed some light on this.
if i use a class that doesen't provide any methods without creating an instance of it, but i skip creating an instance via "new().SomeMethod", will this leak memory?
example, sending an async ping to some host without creating a $Ping Object first:
[System.Net.NetworkInformation.Ping]::new().SendPingAsync($IPAddress)
Usually one would create a $Ping object, ping something and in the end, dispose of the $Ping to free the ressources.
If the SendPingAsync Method could work without an instance of the class, the class probably would have some static method's providing the mechanism. So an instance is probably created somewhere but that instance is probably not automatically disposed after the fact?
Can this method be used without worries or should such trickery be avoided?
thanks in advance
3
u/CeleryMan20 7d ago edited 7d ago
This covers .Net CLR, not PowerShell-specific, but it says that object method code is loaded into the heap:
~https://thinkobjectoriented.hashnode.dev/understanding-static-attributes-and-methods~
I don’t have details on how the PS runspace relates to the CLR, though.
Note that, for OOP generally, if you create 100 instances of a class, you don’t create 100 copies of the class’ methods, regardless of whether they are declared static. The whole point is that instances are stamped from the same cookie cutter and share the same methods.
ETA: The page at that link is a bit flakey for me. Here is Eric Lippert on heap versus stack in .Net CLR. Essentially, method code and much instance data both live on the heap, but it’s implementation-specific. https://learn.microsoft.com/en-au/archive/blogs/ericlippert/the-truth-about-value-types
0
u/ChaosTheoryRules 7d ago
This should clarify things for you.
https://computerthings.substack.com/p/working-with-powershell-static-and
9
u/AdeelAutomates 7d ago edited 7d ago
::new()is the constructor on the class. It creates an instance of Ping (the object).So
.SendPingAsync($IPAddress)is then an instance method being called on that newly created object.So this:
[System.Net.NetworkInformation.Ping]::new().SendPingAsync($IPAddress)is effectively just a shortened version of:
Just without the variable being set.
So the shorthand works, but it does not somehow avoid creating an instance... it just creates a temporary one as part of the cmd and immediately calls the method to output it.