23

I'm quite familiar with VB and .NET in general, but I just ran across this code:

Me.[GetType]()

What is the purpose of the brackets around GetType?

qJake
  • 16,821
  • 17
  • 83
  • 135

1 Answers1

30

The square brackets are used to tell the compiler that he should interpret it as a type, even if it would be a keyword. But your example should be the same as Me.GetType().

You could use it for example for Enums.

Example-Enum:

Enum Colors
    Red
    Green
    Blue
    Yellow
End Enum 'Colors

Dim colors = [Enum].GetValues(GetType(Colors))
For Each c In colors
   Console.WriteLine(c)
Next

That wouldn't compile normally:

Enum.GetValues(GetType(Colors)) 'because Enum is a keyword'
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 4
    Oh okay, so it's the same as @variable in C#. Thanks! – qJake Jun 20 '11 at 17:53
  • In VB6 you could use `[ ]` to create `Enum` values with spaces. I wonder if `VB.NET` is the same way too. – John Alexiou Jul 29 '14 at 14:16
  • No you cannot add spaces to an enum's value. read: http://stackoverflow.com/questions/15458257/how-to-have-enum-values-with-spaces Apart from the suggestion to use `EnumMemberAttribute` you could also use a `Dictionary(Of String, EnumType)` instead where the key is a "friendly" name and the value is the enum. – Tim Schmelter Jul 29 '14 at 14:23
  • In general, the square brackets means "don't treat this as a keyword". For example, this method declaration won't compile "Sub Masquerade(ByVal as As String)"; but this will compile "Sub Masquerade(ByVal [as] As String)" and you can use the variable "[as]" in the body of the method. – Dave Hein Apr 29 '18 at 12:15
  • 1
    You wrote: *"...interpret it as a type"*. I think *"...interpret it as an **identifier**"* would be more precise. In the OP's example, `GetType` is a method name, not a type. – Heinzi Sep 08 '21 at 09:45