I've recently learned a new method [Math].GetMethods()
that returns all the methods the class has. That is perplexing me because I have thought all the static methods of a class in PowerShell must be invoked in form of [Math]::<method_name>
using the Static member operator ::
. And there is no method such as [Math]::GetMethods()
.
Would you help clear up this confusion?
What's the difference between [Math].<method_name>
and [Math]::<method_name>
?
Thank you.
The GetMethods()
comes from Sysem.Type, so you are not calling Math's member at all.
When you use [math]
type accelerator, it will return a RuntimeType object. Like so,
[math].gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
False True RuntimeType System.Reflection.TypeInfo
Now, if one calls Math class static method via member access operator .
like so,
[math].abs(-42)
Method invocation failed because [System.RuntimeType] does not contain a method named 'abs'.
At line:1 char:1
+ [math].abs(-42)
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MethodNotFound
There is an error message. Note that it's System.RuntimeType
that complains for non-existing method abs
.
To call Math's static members, one needs to use static member operator ::
.
[math]::abs(-42)
42