שתף באמצעות


Convert Integer Value to Enum by Using CType or [Enum].Parse?

Question

Sunday, February 10, 2013 7:31 PM

Hello,

Which approach do you think it's best when trying to convert an integer value into an enum? Using CType or [Enum].Parse?

Bianca

All replies (4)

Sunday, February 10, 2013 7:40 PM | 1 vote

Enum.Parse is for converting a string to an enum for example "One"  

An enum will have an integer value so you don't have to cast it to compare it an integer.


Sunday, February 10, 2013 10:04 PM | 1 vote

I agree with Ken.  Also, since you appear to be working with raw integers instead of explicit enum values then you may want to look into the IsDefined function for validation of the int value.

http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx

A failed implicit conversion will cause an exception

Blog: http://codemidden.wordpress.com


Sunday, February 10, 2013 11:26 PM

Hi BiancaG.

Here is some sample code:>>

Option Strict On
Option Explicit On
Option Infer Off

Public Class Form1

    Public Enum ResistorColourCodes
        Brown
        Black
        Red
        Orange
        Yellow
        Green
        Blue
        Violet
        Grey
        White
    End Enum

    Private testValue As Integer = 0

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        testValue = ResistorColourCodes.Blue
        'Shows the value "6"
        '>>
        MessageBox.Show("testValue = " & testValue.ToString)

        testValue = Convert.ToInt32([Enum].Parse(GetType(ResistorColourCodes), "Red", True))
        'Shows the value "2"
        '>>
        MessageBox.Show("testValue = " & testValue.ToString)

    End Sub
End Class
Regards,

Click this link to see the NEW way of how to insert a picture into a forum post.

Installing VB6 on Windows 7

App Hub for Windows Phone & XBOX 360 developers.


Monday, February 11, 2013 5:18 AM | 1 vote

cast it:

dim number as Integer = 3

msgbox(directcast(number, [enumName]))

thanks for any help