Welcome to ciysys blog

Declaring C# like Class type

Published on: 5th Dec 2019

Updated on: 16th Jan 2022

Explanation

If you are familiar with C# or PHP programming language, you will find it quite straightforward to do this in Powershell.

The following sample code explains the basic of declaring class in PowerShell:

# declare a new object type - the same way like C#
class MyObject {
    # instance fields
    [string]$name
    [string]$code
    [int32]$age

    # static fields
    static [int]$objCount

    # constructor
    MyObject ([string]$n){
        $this.name = $n

        # increase the number of instances that have been created.
        [MyObject]::objCount++;
    }

    [string]ToString() {
        #return $this.name
        return "Hello {0}!" -f $this.name
    }
}

# instantiate new instance
##$o = New-Object MyObject "tester"
$o = [MyObject]::new("tester")

##$o.name = "mike"
$o.code = "m001"
$o.age = 38

#show the contents
$o

Write-Host "instance count=$([MyObject]::objCount)"

$s = $o.ToString()
Write-Host "$s"

$j = $o | ConvertTo-Json
Write-Host $j

Use case

References

Jump to #POWERSHELL blog

Author

Lau Hon Wan, software developer.