.Net – Enum – Gets return based on value

Background

I was reading more about enums and noticed a worthy stumble upon by Brian Schroer.

Brian’s Take

Brian’s take is that both of the enum data type Get methods return lists ordered by the enum’s entry assigned value.

Enum

Brian’s list looks like this :-

fieldWidths

Expectation

One might expect the list to be returned as noted during creation.

But, no PowerShell returns an ordered list based on each node’s assigned value.

Code

PowerShell

Script


Set-StrictMode -Version 1.0

enum FieldWidths
{
   CustomerNumber = 5
   OrderNumber = 10
   City = 30
   State = 2
   Zip = 11
}

function listNames( [string[]] $list)
{

    [int] $id=0;
    [string] $formatLog = "{0}) {1}";

    Write-Host "List Names"
    Write-Host "***********"

    $list | ForEach-Object{

        $_obj = $_

        $log = $formatLog -f `
                      ($id +1) `
                    , $_obj `
                    ;

        Write-Host $log -ForegroundColor White; 

        $id = $id + 1;

    }

}

function listValues( [int[]] $list)
{

    [int] $id=0;
    [string] $formatLog = "{0}) {1} {2}";

    Write-Host "List Values"
    Write-Host "***********"

    $list | ForEach-Object{

        $_obj = $_

        $log = $formatLog -f `
                      ($id +1) `
                    , $_obj `
                    , [int] $_obj `
                    ;

        Write-Host $log -ForegroundColor White; 

        $id = $id + 1;

    }

}

[string[]] $listName = $null;
[int[]] $listValue = $null;

$listName = [System.Enum]::GetNames( `
                                    'FieldWidths' `
                                );

$listValue = [System.Enum]::GetValues( `
                                    'FieldWidths' `
                                );

Write-Host; Write-Host

listNames $listName

Write-Host; Write-Host

listValues $listValue

Output

fieldWidths.output

 

Source Code

GitHub

Gist

EnumGetNamesAndGetValuesReturnArraySortedByValue.ps1

Link

Dedicated

Like Wayne, dedicated to the great ones :-

Brian Schroer
Enum.GetValues and Enum.GetNames return arrays sorted by value
Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s