Understanding the .NET Class type in PowerShell

Welcome Forums General PowerShell Q&A Understanding the .NET Class type in PowerShell

This topic contains 2 replies, has 3 voices, and was last updated by

js
 
Participant
3 months, 4 weeks ago.

  • Author
    Posts
  • #109142

    Participant
    Points: 0
    Rank: Member

    I find it's a bit weird to check the type of .NET Class in PowerShell.

    For example, if you issue the command:

    [system.math] | gm

    You'll get a long list of generic members with the type name on the first line:

    TypeName: System.RuntimeType

    But if you run:

    [system.math] | gm -static

    It gives you the real static members of this class with the type:

    TypeName: System.Math

    It looks confusing to me. From my understanding, the -static parameter only tells the command to retrieve static members but should not affect the type if returns.

    Can anyone explain why it behaves like this?

    Thanks.

     

  • #109493

    Participant
    Points: 12
    Rank: Member

    You are getting System.RuntimeType in the output because system.math is a class type not an object.  You will get the same results when piping System.Int32 to gm:

    
    [System.Int32] | gm
    
    TypeName: System.RuntimeType
    
    

     

    However, when you create integer object "73" using system.int32 and pass it to gm, you will get a System.Int32 object, along with its static methods.

    
    PS C:\WINDOWS\system32> [system.int32]73 | gm
    
    TypeName: System.Int32
    
    

    I hope this helps.

     

     

  • #109508
    js

    Participant
    Points: 327
    Helping Hand
    Rank: Contributor
    # static method
    PS /Users/js> [System.Math]::sqrt(4)                                                                             
    2
    
    PS /Users/js> $ping = [System.Net.Networkinformation.ping]::new()                                                                                                                                       
    # instance method
    PS /Users/js> $ping.send('yahoo.com')                                                                            
    Status        : Success
    Address       : 2001:4998:58:1836::11
    RoundtripTime : 31
    Options       : 
    Buffer        : {}

The topic ‘Understanding the .NET Class type in PowerShell’ is closed to new replies.