Search code examples
vb.netstrict

Need help translating vb.net line to be strict proof


I am having issues with translating this vb.net line into a strict proof one

[Enum].GetValues(GetType(ReferenceOutput))(DataGrid1.SelectedIndex)

ReferenceOutput is a class and the datagrid1.selectedindex is the one selected in the datagrid . How do I translate this into a strict proof line. I get followin error now.

Error   1   Option Strict On disallows late binding.

Thanks


Solution

  • The most robust approach would be to use Enum.TryParse which is a new generic method:

    Dim refOutput As ReferenceOutput
    Dim enumValue = DataGrid1.SelectedIndex.ToString()
    If [Enum].TryParse(enumValue, refOutput) Then
        Console.WriteLine("Converted '{0}' to {1}.", enumValue, refOutput.ToString())
    Else
        Console.WriteLine("{0} is not a member of the ReferenceOutput enumeration.", enumValue)
    End If
    

    This is the old verbose, unchecked unboxing approach:

    Dim refOutput As ReferenceOutput = DirectCast([Enum].Parse(GetType(ReferenceOutput), DataGrid1.SelectedIndex.ToString(), True), ReferenceOutput)