Module Module1
Enum Colors
Red
Green
Blue
Yellow
End Enum
Sub main()
Dim values = [Enum].GetValues(GetType(Colors)) ' Statement 1
Console.WriteLine(values.GetType) 'O/P: Colors[]
Console.ReadLine()
End Sub
End Module
Values
expectedly is of type Colors[]
. Now my question is which of the overloaded versions of GetValues is being executed here? To put this in context the basic GetValues method returns an Array
type whereas the overloaded version returns TEnum[]
type. Since Values
is not of Array
type and is of a specific enum array type (in this case Colors[]
, I am inferring that statement 1 is calling the overloaded version of the GetValues method.
Adding the MSDN GetValues page for quick reference.
My Questions:
- Is the above understanding right?
- If not can someone pls give an example where we are using the overloaded version of the GetValues method that returns the
TEnum[]
type?
Also, as I understand from an answer posted by @John that the GetValues method that returns Array
type is pre-generics and is not being called in the statement GetValues(GetType(Colors))
. Is this understanding correct?
CodePudding user response:
EDIT:
I just realised that the generic overload was only introduced in .NET 5, so any earlier versions can only use the non-generic version. That means .NET Core 3.1 or earlier and any version of .NET Framework. It is always a good idea to read the documentation and confirm exactly what .NET versions a type or method applies to.
ORIGINAL:
Either will work but the first was authored when generics didn't exist. Generic methods are generally better than non-generic ones. You can do this:
Dim values = [Enum].GetValues(GetType(Colors))
or this:
Dim values = [Enum].GetValues(Of Colors)()
and, in the second one, the variable will be type Colors()
, which is really what you want.
As for that As Structure
generic constraint, it's there because that's as close as you can get to constraining TEnum
to be an actual Enum
. You can't actually constrain it that far but at least you can constrain it to be a structure, so no one can specify a class when calling that method. As Enums
are structures under the hood, because they are all numeric types - Integer
by default - under the hood. Someone could still specify a structure that isn't an Enum
when calling that method, but the non-generic method would allow them to specify a class as well.