You are not logged in.

#1 14 Dec 2016 23:20

kingtermite
Member
Registered: 28 Oct 2016
Posts: 18

string vs. object issue

It seems that when I return a string from a function it is then an object on the other side. Even when I convert it, I just want the "string". Why is this so elusive?

Simplified code sample:

function Get-SN
{
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
    Add-Type -AssemblyName Microsoft.VisualBasic

    $sn = [string] [Microsoft.VisualBasic.Interaction]::InputBox("Enter s/n:`n", 'Serial Number')
    Write-Warning($sn)
    Write-Warning("Type: " + $sn.GetType())
    
    return $sn
}




[string] $mySN = Get-SN
Write-Warning($mySN)
Write-Warning("Type: " + $mySN.GetType())
$t = $mySN.ToString()
Write-Warning($t)
Write-Warning("Type: " + $t.GetType())

So, when the UI displays I give "aaa" as the value. See the console output:


WARNING: aaa
WARNING: Type: string
WARNING: System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 aaa
WARNING: Type: string
WARNING: System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 aaa
WARNING: Type: string

Once it returns from the function, I've cast to a string, but I appear to be getting the string representation of the string object.

I was expect "aaa" as the print out from inside the function, but instead I get "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 aaa"

This has to be simple...I don't know I'm struggling on this, but I can't seem to find the answer.

Offline

#2 14 Dec 2016 23:41

kingtermite
Member
Registered: 28 Oct 2016
Posts: 18

Re: string vs. object issue

LOL...lately when I post a question here, I FINALLY find the answer right after I post.

The trick was how the assembly is loaded. Corrected version of function.

function Get-SN
{
    #[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
    #Add-Type -AssemblyName Microsoft.VisualBasic
    [Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")

    $sn = [string] [Microsoft.VisualBasic.Interaction]::InputBox("Enter s/n:`n", 'Serial Number')
    Write-Warning($sn)
    Write-Warning("Type: " + $sn.GetType())
    
    return $sn
}

Offline

Board footer

Powered by