Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/e17fa71083847c9ba78d to your computer and use it in GitHub Desktop.
Save guitarrapc/e17fa71083847c9ba78d to your computer and use it in GitHub Desktop.
PowerShell Class Constructor Sample
########################
# Constructor Call check
########################
class Hoge
{
Hoge()
{
Write-Host "constuctor called"
}
}
[Hoge]::new()
<#
constuctor called
#>
########################
# Initialization
########################
class MyClass
{
[string]$name
[int]$age
MyClass()
{
$name = ""
$age = 0
}
}
[MyClass]::new()
<#
name age
---- ---
0
#>
########################
# This not supported
########################
class MyClass
{
[string]$name;
MyClass([string]$name)
{
$name = $name #this not yet usable
}
}
[MyClass]::new("hoge")
<#
name
----
#>
########################
# Constructor can overload
########################
class MyClass
{
[string]$name
[int]$age
MyClass()
{
$name = ""
$age = 0
}
MyClass([string]$hoge, [int]$fuga)
{
$name = $hoge
$age = $fuga
}
}
[MyClass]::new
<#
OverloadDefinitions
-------------------
MyClass, powershell, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null new()
MyClass, powershell, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null new(string hoge, int fuga)
#>
[MyClass]::new("hoge", 10)
<#
name age
---- ---
hoge 10
#>
@guitarrapc
Copy link
Author

"constuctor called"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment