r/PowerShell • u/xXFl1ppyXx • Oct 20 '26
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
View all comments
Show parent comment
0
u/Thotaz Oct 20 '26
Ideally you always run
Dispose()if your object implements that method. However, if you don't do that then it's usually not a big deal because those objects will also usually implement a custom finalizer that makes sure to do the proper disposing when the garbage collector sees that there are no references to the object anymore.In the shell, I wouldn't worry about it. In a script, I'd put
Disposein a finally block, like so: