I have several class modules (let's assume classA, classB and so on) created for different purposes. From the main file, I want to create instance dynamically from each class
Rather than creating instance one by one like below, I want to create them dynamically through a loop. The below "classname" value cannot be replaced by a variable ($classname) as I checked. Any proper method to get this done?
[<classname>]$instance = [<classname>]::new()
You can use the -as
operator or simply cast [type]
to instantiate them, for example:
class A {
$prop = 'classA'
}
class B {
$prop = 'classB'
}
class C {
$prop = 'classC'
}
foreach ($i in 'A', 'B', 'C') {
($i -as [type])::new() # with `-as`
([type] $i)::new() # casting
}
Assuming you will be instantiating many times using this method, it will be preferable to cache the types in different variables (using class A
as example):
$classA = 'A' -as [type]
0..10 | ForEach-Object {
$classA::new()
}
Alternatively, personally wouldn't recommend this method, but you can use New-Object
:
foreach ($i in 'A', 'B', 'C') {
New-Object $i
}