Thursday, May 5, 2011

[String] vs String in .NET

I used developerfusion.com to convert a snippet of my C# code to VB .NET and I noticed the String type translated into [String].

I tried Google and Searching SO to no avail so I will ask the community is there a difference between [String] and String? And if so what is/are the difference(s)?

From stackoverflow
  • Brackets usually indicate a variable name that using a reserved keyword. Did you name string variables String?

  • In VB.Net, the [] surrounding a word is used to allow a keyword to be used as a normal identifier. So using [String] means I want to identify something with the word String and not the VB keyword String.

    PersistenceOfVision : Thank Jared! Your answer and Guffa's were acceptable. So I up voted your answer and accepted Guffa's due to Guffa's answer came in before yours and included an example. Again Thank you to both of you!
    ShuggyCoUk : For c# developers it is the equivalent of @ in front of variable names like @this
  • The converter probably did that because it didn't recognise the string type and thought that it was a class defined in your code.

    You can put brackets around identifiers to use keywords. You could create your own [String] class that would be different from the built in String class, but that could of course easily get confusing...

    Public Class [String]
       Public Value As Integer
    End Class
    
    Dim s As New [String]
    s.Value = 42
    
  • Brackets can be used in VB.NET to allow VB.NET keywords to be used as user defined names. For example, you could create a class called Integer, even though there is already an Integer keyword in VB.NET:

    Public Class [Integer]
    End Class
    

    Hope this clearifies!

0 comments:

Post a Comment