Why does string not require a new like other reference types?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ray Cassick

    Why does string not require a new like other reference types?

    I can't believe why I had not noticed this before and why I never asked it
    before...

    When defining a string why is it not required to use the new keyword? Like:

    Dim a As String = New String

    You can do it when using the string type with some arguments in the
    constructor but it look like there is no empty constructor on the String
    class.

    Seem odd to me that all the other reference types seem to require a new to
    create the instance portion of the type and String does not.

    Thanks for any insight...


  • =?ISO-8859-1?Q?G=F6ran_Andersson?=

    #2
    Re: Why does string not require a new like other reference types?

    Ray Cassick wrote:
    I can't believe why I had not noticed this before and why I never asked it
    before...
    >
    When defining a string why is it not required to use the new keyword? Like:
    >
    Dim a As String = New String
    >
    You can do it when using the string type with some arguments in the
    constructor but it look like there is no empty constructor on the String
    class.
    >
    Seem odd to me that all the other reference types seem to require a new to
    create the instance portion of the type and String does not.
    >
    Thanks for any insight...
    >
    If you declare a string without assigning a value to it, you haven't
    created any instance of the string class, you have only declared a
    reference.

    All literal string values are created as constants in the assembly. As
    they already exists when the code is started, you don't need to use the
    new keyword when assigning them.

    --
    Göran Andersson
    _____
    Göran Anderssons privata hemsida.

    Comment

    • Herfried K. Wagner [MVP]

      #3
      Re: Why does string not require a new like other reference types?

      "Ray Cassick" <rcassick@enter procity.comschr ieb:
      When defining a string why is it not required to use the new keyword?
      Like:
      >
      Dim a As String = New String
      Because it would not make sense. Strings are immutable in .NET. If you
      write 'Dim a As String = "Hello World"' you are creating an instance of
      'String' containing "Hello World" and assign a reference to it to the
      variable 'a'. Each assignment to a 'String' variable changes the reference.
      You can do it when using the string type with some arguments in the
      constructor but it look like there is no empty constructor on the String
      class.
      Which value should a string constructed with the parameterless constructor
      have?

      --
      M S Herfried K. Wagner
      M V P <URL:http://dotnet.mvps.org/>
      V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

      Comment

      • Ray Cassick

        #4
        Re: Why does string not require a new like other reference types?


        "Herfried K. Wagner [MVP]" <hirf-spam-me-here@gmx.atwrot e in message
        news:eaRQIIXyIH A.4376@TK2MSFTN GP06.phx.gbl...
        "Ray Cassick" <rcassick@enter procity.comschr ieb:
        >When defining a string why is it not required to use the new keyword?
        >Like:
        >>
        >Dim a As String = New String
        >
        Because it would not make sense. Strings are immutable in .NET. If you
        write 'Dim a As String = "Hello World"' you are creating an instance of
        'String' containing "Hello World" and assign a reference to it to the
        variable 'a'. Each assignment to a 'String' variable changes the
        reference.
        >
        >You can do it when using the string type with some arguments in the
        >constructor but it look like there is no empty constructor on the String
        >class.
        >
        Which value should a string constructed with the parameterless constructor
        have?
        >
        Thanks for the response...

        So as I understood it (and the way it was actually taught to me) is this.

        When you do this:

        Dim a As TypeName

        The storage is declared on the managed stack. IF the type is a ValueType
        then nothing else is needed and the storage is all done on the stack. IF the
        type is a reference type then the stack storage ends up just being a pointer
        that will end up being an address on the heap somewhere but points to
        nowhere just yet.

        When you do this:

        Dim a As ClassName = New ClassName...

        THEN the storage is allocated on the stack AND the storage is allocated on
        the heap and the stack points to the proper location on the heap.

        So, I guess my question is.. if String is a reference type why do you NOT
        NEED to allocate it using the New keyword every time? Almost seems like
        strings are an odd case with respect to this.

        I would expect that doing this:

        Dim a As String

        would simply point to nothing (as it does) just like doing this:

        Dim a As Integer

        results in a 0.

        I am just curious as to why the String type seems to be inconsistent in
        behavior with respect to other reference types.



        Comment

        • Steve Gerrard

          #5
          Re: Why does string not require a new like other reference types?

          Ray Cassick wrote:
          >
          So, I guess my question is.. if String is a reference type why do you
          NOT NEED to allocate it using the New keyword every time? Almost
          seems like strings are an odd case with respect to this.
          >
          I am just curious as to why the String type seems to be inconsistent
          in behavior with respect to other reference types.
          Although a String is technically a reference type, it has behavior more like a
          value type. The actual string of characters is "immutable" , making it unlike
          most other object classes. A new string is created with every assignment
          statement (or the string variable points to a stored literal).

          Dim Test As String
          ' points to nothing

          Test = "Hello"
          ' points to the stored literal "Hello"

          Test = Test + ", "
          ' points to a new string containing "Hello, "

          Test = Test + "World"
          ' points to a new string containing "Hello, World"

          Test = Test.ToUpper
          ' points to a new string containing "HELLO, WORLD"



          Comment

          • Cor Ligthert[MVP]

            #6
            Re: Why does string not require a new like other reference types?

            Ray,

            Your replies sounds to me like somebody driving a car once heard that there
            was a carburator in it, and now ask why he cannot find it in his current
            car.

            It is important for a driver, that a car do exactly as it should do? You are
            not the one who designs Net and the way it works.

            By the way, playing with words does not work here.

            Dim a as integer "results" in a 0
            Dim b as string "results" in a ""

            Both as with all valuetypes with the lowest value possible.

            Strange that you did not mention the Struct DateTime which has almost the
            same behaviours

            Just my idea reading your replies.

            Cor

            "Ray Cassick" <rcassick@enter procity.comschr eef in bericht
            news:e1SfVFcyIH A.2064@TK2MSFTN GP05.phx.gbl...
            >
            "Herfried K. Wagner [MVP]" <hirf-spam-me-here@gmx.atwrot e in message
            news:eaRQIIXyIH A.4376@TK2MSFTN GP06.phx.gbl...
            >"Ray Cassick" <rcassick@enter procity.comschr ieb:
            >>When defining a string why is it not required to use the new keyword?
            >>Like:
            >>>
            >>Dim a As String = New String
            >>
            >Because it would not make sense. Strings are immutable in .NET. If you
            >write 'Dim a As String = "Hello World"' you are creating an instance of
            >'String' containing "Hello World" and assign a reference to it to the
            >variable 'a'. Each assignment to a 'String' variable changes the
            >reference.
            >>
            >>You can do it when using the string type with some arguments in the
            >>constructor but it look like there is no empty constructor on the String
            >>class.
            >>
            >Which value should a string constructed with the parameterless
            >constructor have?
            >>
            >
            Thanks for the response...
            >
            So as I understood it (and the way it was actually taught to me) is this.
            >
            When you do this:
            >
            Dim a As TypeName
            >
            The storage is declared on the managed stack. IF the type is a ValueType
            then nothing else is needed and the storage is all done on the stack. IF
            the type is a reference type then the stack storage ends up just being a
            pointer that will end up being an address on the heap somewhere but points
            to nowhere just yet.
            >
            When you do this:
            >
            Dim a As ClassName = New ClassName...
            >
            THEN the storage is allocated on the stack AND the storage is allocated on
            the heap and the stack points to the proper location on the heap.
            >
            So, I guess my question is.. if String is a reference type why do you NOT
            NEED to allocate it using the New keyword every time? Almost seems like
            strings are an odd case with respect to this.
            >
            I would expect that doing this:
            >
            Dim a As String
            >
            would simply point to nothing (as it does) just like doing this:
            >
            Dim a As Integer
            >
            results in a 0.
            >
            I am just curious as to why the String type seems to be inconsistent in
            behavior with respect to other reference types.
            >
            >
            >

            Comment

            • =?ISO-8859-1?Q?G=F6ran_Andersson?=

              #7
              Re: Why does string not require a new like other reference types?

              Cor Ligthert[MVP] wrote:
              Ray,
              >
              Your replies sounds to me like somebody driving a car once heard that
              there was a carburator in it, and now ask why he cannot find it in his
              current car.
              >
              It is important for a driver, that a car do exactly as it should do? You
              are not the one who designs Net and the way it works.
              >
              By the way, playing with words does not work here.
              >
              Dim a as integer "results" in a 0
              Dim b as string "results" in a ""
              Not at all. Declaring a string without assigning a value either results
              in a null reference (for member variables) or an undefined variable (for
              local method variables).
              Both as with all valuetypes with the lowest value possible.
              String is not a value type, so the default value for string is not an
              empty string, it's null.
              Strange that you did not mention the Struct DateTime which has almost
              the same behaviours
              >
              Just my idea reading your replies.
              >
              Cor
              >
              --
              Göran Andersson
              _____
              Göran Anderssons privata hemsida.

              Comment

              • Cor Ligthert [MVP]

                #8
                Re: Why does string not require a new like other reference types?


                "Göran >>
                >Dim a as integer "results" in a 0
                >Dim b as string "results" in a ""
                >
                Not at all. Declaring a string without assigning a value either results in
                a null reference (for member variables) or an undefined variable (for
                local method variables).
                >
                I especially placed the double quotes around the words results.

                As a string is declared then the type Is String and the object Is Nothing.
                As soon as you use a string then it will create that empty string. Even as
                that is If string = nothing

                :-)

                Cor



                Comment

                • Cor Ligthert [MVP]

                  #9
                  Re: Why does string not require a new like other reference types?

                  Goran,

                  By the way, are you using often C#, because this misunderstandin g is
                  typically from people only using that?

                  Cor


                  Comment

                  • Jack Jackson

                    #10
                    Re: Why does string not require a new like other reference types?

                    On Sun, 8 Jun 2008 19:39:09 -0400, "Ray Cassick"
                    <rcassick@enter procity.comwrot e:
                    >
                    >So, I guess my question is.. if String is a reference type why do you NOT
                    >NEED to allocate it using the New keyword every time? Almost seems like
                    >strings are an odd case with respect to this.
                    >
                    >I would expect that doing this:
                    >
                    >Dim a As String
                    >
                    >would simply point to nothing (as it does) just like doing this:
                    >
                    >Dim a As Integer
                    >
                    >results in a 0.
                    >
                    >I am just curious as to why the String type seems to be inconsistent in
                    >behavior with respect to other reference types.
                    Strings are an odd case because they are a reference type that is
                    created by using a language constant. If strings required New, then
                    every use of a string constant would require New:

                    Dim a As String = New String("abc") + New String("def")
                    MessageBox.Show (New String("Some message"))

                    That's a lot of typing and a lot of clutter for no purpose. Requiring
                    New provides no functionality over just using the constant by itself.

                    Comment

                    • Brian Gideon

                      #11
                      Re: Why does string not require a new like other reference types?

                      On Jun 9, 5:40 am, "Cor Ligthert [MVP]" <notmyfirstn... @planet.nl>
                      wrote:
                      As a string is declared then the type Is String and the object Is Nothing.
                      As soon as you use a string then it will create that empty string. Even as
                      that is If string = nothing
                      >
                      :-)
                      >
                      Cor
                      That is not a true statement. Consider the following trivial example.

                      Dim a As String
                      a.ToString()

                      The example uses "a" before it is assigned and that generates a
                      NullReferenceEx ception as you would expect from any reference type.
                      An empty string did not get created and assigned to "a" at any point.

                      Comment

                      • Cor Ligthert[MVP]

                        #12
                        Re: Why does string not require a new like other reference types?

                        Brian,

                        You are right, however I seldom set a string to a string.

                        This works
                        Dim a As String
                        TextBox1.Text = a

                        Cor

                        Comment

                        • Brian Gideon

                          #13
                          Re: Why does string not require a new like other reference types?

                          On Jun 9, 11:10 am, "Cor Ligthert[MVP]" <notmyfirstn... @planet.nl>
                          wrote:
                          Brian,
                          >
                          You are right, however I seldom set a string to a string.
                          I'm not sure what you mean by that.
                          >
                          This works
                          Dim a As String
                          TextBox1.Text = a
                          >
                          Cor
                          That works because TextBox.Text checks to see if the value being
                          assigned is a null reference first and if it is then it creates an
                          empty string and assigns that instead (I checked using Reflector).
                          That behavior is specific to TextBox (and perhaps other classes in the
                          BCL as well) and cannot be generalized to every use of a string.

                          Comment

                          • Jack Jackson

                            #14
                            Re: Why does string not require a new like other reference types?

                            On Mon, 9 Jun 2008 09:48:11 -0700 (PDT), Brian Gideon
                            <briangideon@ya hoo.comwrote:
                            >On Jun 9, 11:10 am, "Cor Ligthert[MVP]" <notmyfirstn... @planet.nl>
                            >wrote:
                            >Brian,
                            >>
                            >You are right, however I seldom set a string to a string.
                            >
                            >I'm not sure what you mean by that.
                            >
                            >>
                            >This works
                            >Dim a As String
                            >TextBox1.Tex t = a
                            >>
                            >Cor
                            >
                            >That works because TextBox.Text checks to see if the value being
                            >assigned is a null reference first and if it is then it creates an
                            >empty string and assigns that instead (I checked using Reflector).
                            >That behavior is specific to TextBox (and perhaps other classes in the
                            >BCL as well) and cannot be generalized to every use of a string.
                            Another oddity of strings is that test for equality with an empty
                            string doesn't trap if the string reference is Nothing, but any other
                            use of the reference to Nothing does trap.

                            Dim a As String = Nothing
                            If a = "" Then ' This doesn't trap, unlike other reference types
                            If a.Length 0 Then ' This does trap like other reference types

                            I'm not sure why it works this way. While this behavior can be
                            convenient (saving a test for Is Nothing), it only helps when
                            comparing for the empty string.

                            It's another example of how String is treated as a cross between
                            reference and value types.

                            Comment

                            • =?ISO-8859-1?Q?G=F6ran_Andersson?=

                              #15
                              Re: Why does string not require a new like other reference types?

                              Jack Jackson wrote:
                              On Sun, 8 Jun 2008 19:39:09 -0400, "Ray Cassick"
                              <rcassick@enter procity.comwrot e:
                              >
                              >So, I guess my question is.. if String is a reference type why do you NOT
                              >NEED to allocate it using the New keyword every time? Almost seems like
                              >strings are an odd case with respect to this.
                              >>
                              >I would expect that doing this:
                              >>
                              >Dim a As String
                              >>
                              >would simply point to nothing (as it does) just like doing this:
                              >>
                              >Dim a As Integer
                              >>
                              >results in a 0.
                              >>
                              >I am just curious as to why the String type seems to be inconsistent in
                              >behavior with respect to other reference types.
                              >
                              Strings are an odd case because they are a reference type that is
                              created by using a language constant. If strings required New, then
                              every use of a string constant would require New:
                              >
                              Dim a As String = New String("abc") + New String("def")
                              MessageBox.Show (New String("Some message"))
                              >
                              That's a lot of typing and a lot of clutter for no purpose. Requiring
                              New provides no functionality over just using the constant by itself.
                              Besides, when you use a literal string it's not created when you use it.
                              It already exists as a constant in the assembly, so if New was requiered
                              like that, the compiler would actually replace each New call with the
                              reference to the string constant.

                              You can verify that using a string literal doesn't create any new object
                              like this:

                              Dim x(1) As String
                              For i As Integer = 0 to 1
                              x(i) = "asdf"
                              Next
                              Console.WriteLi ne(Object.Refer enceEquals(x(0) , x(1)).ToString( ))

                              It will write out True, as the code in the loop assigns the reference of
                              the same string literal to both the items in the array.

                              You can also verify that string literals are reused like this:

                              Console.WriteLi ne(Object.Refer enceEquals("asd f", "asdf").ToStrin g())

                              It will write out True, as the same string constant is used for both
                              string literals.

                              --
                              Göran Andersson
                              _____
                              Göran Anderssons privata hemsida.

                              Comment

                              Working...