Skip to content

Instantly share code, notes, and snippets.

@ScottHutchinson
Last active June 22, 2018 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ScottHutchinson/1c6aa46e7c9f78c86ddfe1ace1a4594f to your computer and use it in GitHub Desktop.
Save ScottHutchinson/1c6aa46e7c9f78c86ddfe1ace1a4594f to your computer and use it in GitHub Desktop.
VB Generic Function for converting an Integer to an Enum
Module Module1
Public Enum MediaType
Audio
Video
Image
End Enum
Public Function IntToEnumOrNothing(Of T As {IConvertible, Structure})(ByVal value As Integer) As T?
Dim ret As T? = Nothing
If [Enum].IsDefined(GetType(T), value) Then
ret = CType([Enum].ToObject(GetType(T), value), T?) ' CType(value, T) would not work in this context.
End If
Return ret
End Function
Sub Main()
Dim x As MediaType? = IntToEnumOrNothing(Of MediaType)(1)
Console.WriteLine("x = {0}", x.Value) ' --> x = Video
Dim y As MediaType? = IntToEnumOrNothing(Of MediaType)(55)
Console.WriteLine("y has value: {0}", y.HasValue) ' --> y has value: False
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment