Reputation: 5004
Edited #3.
I managed to get it working. I need to load all dependencies in the correct order in the main script file. not from the class file so I will vote it to close this post.
I am using powershell 5.0 on Windows 10. Using List (e.g. $list = New-Object System.Collections.Generic.List``1[CustomClass]
) works in most of the cases. But got the error when I used it as a return type.
The code below doesn't work.
class CustomClass1 {
[System.Collections.Generic.List``1[CustomClass]]GetColumns([string]$tableType){
$list = New-Object System.Collections.Generic.List``1[CustomClass]
return $list
}
}
Edited: #1
I tried this code below but didn't work as well.
[System.Collections.Generic.List``1[CustomClass]]GetColumns([string]$tableType) {
$list = New-Object System.Collections.Generic.List``1[CustomClass]
$c= New-Object CustomClass
$list.Add($c)
return ,$list
}
Edited: #2
I push my test scripts in this repo https://github.com/michaelsync/powershell-scripts/tree/master/p5Class
CustomClass.ps1
class CustomClass {
[string]$ColumnName
}
CustomClass1.ps1
. ".\CustomClass.ps1"
class CustomClass1 {
[System.Collections.Generic.List``1[CustomClass]]GetColumns(){
$list = New-Object System.Collections.Generic.List``1[CustomClass]
$c = New-Object CustomClass
$list.Add($c)
return $list
}
}
Test.ps1
. ".\CustomClass1.ps1"
$c1 = New-Object CustomClass1
$c1.GetColumns()
If I put all classes in one file, it works. I think it has something to do with the way the ps1 files are being loaded. (Thanks @jesse for the tip. )
But if I use normal type such as string, int and etc, it works.
class CustomClass1 {
[System.Collections.Generic.List``1[string]]GetColumns([string]$tableType){
$list = New-Object System.Collections.Generic.List``1[string]
return $list
}
}
It also works when I assign the generic list with custom class.
$list = New-Object System.Collections.Generic.List``1[CustomClass]
$c = New-Object CustomClass
$list.Add($c)
Is that the known issue that we can't return the generic list with custom class type?
Upvotes: 1
Views: 2404
Reputation: 114887
Your error "Unable to find type [CustomType]" indicates that there is an issue in the order in which types are loaded, or that you've missed loading a dependency (be it a script or an assembly) completely.
Check that before your functions are used, all the scripts and assemblies are loaded.
Upvotes: 1