r/PowerShell • • 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

4 Upvotes

11 comments sorted by

View all comments

Show parent comment

2

u/CeleryMan20 Oct 20 '26

Even if you dispose the instance, does that cause the class definition to be collected? I would expect a managed-code environment would keep it loaded for a while, in case you want to create a new instance.

2

u/Thotaz Oct 20 '26

I'm no expert, but I don't think a type definition gets garbage collected. Once an assembly has been loaded, the type definitions within are always available.

1

u/dodexahedron Oct 20 '26

Correct. At least in Core, since there is only one app domain.

Windows PowerShell you supposedly can manage to unload things but I can't remember ever successfully doing so in any practical scenario (or any at all?🤔).