[String]

G

Guest

Someone please tell me when to use [String] in VB.Net. I see strings dimmed
like:
Dim sStr as string
I also see:
Dim sStr as [String]

What is the difference?
 
J

Jay B. Harlow [MVP - Outlook]

Robert
The brackets allow you to use a Keyword as an identifier. The first is using
String as a keyword, the second is using String specifically as an
identifier.

Seeing as the String keyword in VB.NET is simply an alias for System.String,
and System is normally always imported, there is no difference, they are
semantically identical.


The only time that they would not be semantically identical is if you
defined a String type in your project.

Public Class [String]
End Class

In this case the brackets are required as I am using String as an
identifier. The String keyword would continue to be a keyword, an alias to
System.String, while [String] would be an identifier to my String class.

Dim a As [String] ' defines a MyProject.String variable
Dim b As String ' defines a System.String variable

If a = b Then ' fails as MyProject.String cannot be compared to
System.String

End If

I rarely use [] on String as I do not redefined String as my sample above
showed. I will use [] on other keywords that I want to use a method
(Property, Sub, Function, Event) on a type.

For example:

Public Class IntegerRange
Public Start As Integer
Public [End] As Integer

Public Function Contains(value As Integer) As Boolean
End Class

End is a keyword, so I could not use it as the End point of the above Range
without the brackets. When I use the above type in a program, End is
normally a qualified name, so I normally don't need brackets.

Dim range As IntegerRange
range.Start = 100
range.End = 200

If range.Contains(50) Then
End if

Hope this helps
Jay

Hope this helps
Jay
 
C

Cor Ligthert

Robert,

You see this sometimes stupidly used on MSDN. The samples from the beginning
seems for me just a kind of translated C# samples, most likely by C# guys or
girls. From the newer you can see that the ones who make those know more
from VBNet. That is the way I look at those samples.

I hope that helps,

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top