Last active
June 22, 2018 18:41
-
-
Save ScottHutchinson/1c6aa46e7c9f78c86ddfe1ace1a4594f to your computer and use it in GitHub Desktop.
VB Generic Function for converting an Integer to an Enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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