locked
Square Brackets Around variable Names RRS feed

  • Question

  • User2023521679 posted

    I was looking at an example of how to use System.Net.Mail when I came across the following example. I am unfamiliar with the square brackets around the [from] and [to] in the code sample below. What do the brackets do. Is there a good web site to explain this?

    Public Shared Sub CreateTestMessage(ByVal server As String)
          Dim [from] As New MailAddress("R.Pzak@AMittal.com")
          Dim [to] As New MailAddress("R.Pzak@AMittal.com")
          Dim EMailMessage As New MailMessage([from], [to])
          EMailMessage.Subject = "Using the SmtpClient class."
          EMailMessage.Body = "Using this feature, you can send an e-mail message from an application very easily."
          Dim client As New SmtpClient(server)
          Console.WriteLine("Sending an e-mail message to {0} by using SMTP host {1} port {2}.", [to].ToString(), client.Host, client.Port)
    
          Try
             client.Send(EMailMessage)
    
          Catch ex As Exception
             Console.WriteLine("Exception caught in CreateTestMessage4(): {0}", ex.ToString())
          End Try
       End Sub

    Tuesday, December 10, 2013 11:22 AM

Answers

  • User397347636 posted

    The square brackets just allow you to use keywords as identifiers.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 10, 2013 11:26 AM

All replies

  • User397347636 posted

    The square brackets just allow you to use keywords as identifiers.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 10, 2013 11:26 AM
  • User2103319870 posted

    Hi,

    THe square brackets is used so that the compiler interprets it as a type, even if it would be a keyword. 

    If we take your sample code

            Dim [to] As New MailAddress("R.Pzak@AMittal.com")

    Here "to" is a keyword in VB.Net and if you used it with  out square brackets[] you will get an exception saying that

    Keyword is not valid as an identifier.

    To resolve this issse we use [] 

    Check the below discussion which contains details explanations on the same topic

    What do square brackets around an identifier in VB.NET signify?

    What does [String] mean in VB.NET?

    Tuesday, December 10, 2013 11:30 AM
  • User2023521679 posted

    Okay, I think I get it. "from" and "to" are keywords, yet whoever created the example wanted to use these as identifiers, so the author surrounded these in square brackets. It probably would have been a better idea to rename these to something like ToEMailAddress and FromEMailAddress instead and remove the square brackets.

    Tuesday, December 10, 2013 11:35 AM