views:

80

answers:

3

I ran some code through an automatic translator for C# to VB, and it translated some code like this:

Public Property Title As [String]

How is this different to

Public Property Title As String

and why do both exist?

+11  A: 

String is a keyword. If you want to use a keyword as an identifier, you'll have to enclose it in brackets. [String] is an identifier. String keyword always refers to System.String class while [String] can refer to your own class named String in the current namespace. Assuming you have Imports System, both refer to the same thing most of the time but they can be different:

Module Test
    Class [String]
    End Class
    Sub Main()
        Dim s As String = "Hello World"        // works
        Dim s2 As [String] = "Hello World"     // doesn't work
    End Sub
End Module

The primary reason for existence of [ ] for treating keywords as identifiers is interoperability with libraries from other languages that may use VB keywords as type or member names.

Mehrdad Afshari
Great answer, thanks.
SLC
Wonderfull and correct answer.
chrissie1
+1  A: 

[] allows you to use VBs keywords as identifiers, just like @ in c#. it is useless here.

Andrey
A: 

In that example, they do nothing.(*) You can use brackets to use reserved words as identifiers, though. E.g.: Dim [String] as String

EDIT: (*) Unless they've defined their own class called [String] that they could be referring to

Tim Goodman