Results 1 to 16 of 16

Thread: Why do primitive types not require the 'NEW' keyword?

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jan 2022
    Posts
    26

    Why do primitive types not require the 'NEW' keyword?

    Beginner at VB.NET here. Just a noob question for the experts...

    I've read at various places in an OOP language, everything is an "object". And I was amazed to see that a variable of type STRING has properties that can be accessed. This is awesome.

    It never occurred to me until now that a STRING, for instance (pun intended?), doesn't require the 'NEW' keyword.

    So my question(s) is, is the STRING primitive type actually an object? A structure?

    Is it merely a matter of the inner workings of the language itself?

    Thanks

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Why do primitive types not require the 'NEW' keyword?

    String is a class and works exactly like all other classes, e.g. if you declare a variable of type String and don't initialise it then the variable is Nothing and refers to no object, so trying to access members will throw a NullReferenceException.

    When you declare a variable, a memory location is allocated for it and filled with zero bits, which corresponds to Nothing. What Nothing means depends on the type. All reference type (class) variables contain the memory location of an object, so Nothing means no object. All value type (structure) variables contain a value, so Nothing represents the default value for that type. That means the number zero for numeric types, False for Boolean, midnight on the morning of January 1, 0001 for DateTime, etc.

    There are two reasons that String seems to behave like a value type when its actually a reference type. Firstly, as with pretty much all programming languages, VB supports literal Strings. That is why you can create a String object without invoking a constructor with the New keyword. Secondly, Strings are immutable, meaning that you cannot change a String object once you've created it. If you take these two things into account, you can see how Strings still behave like other reference types. String is not the only class that is immutable, e.g. Font, and it is not even the only one that supports literals, as VB also supports XML literals.

  3. #3
    Frenzied Member
    Join Date
    Apr 2016
    Posts
    1,415

    Re: Why do primitive types not require the 'NEW' keyword?

    John,

    Nothing is not a valid value for a reference type variable. A reference type variable is assigned a reference to an object OR it is assigned the special value null (the absence of an object reference)

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Why do primitive types not require the 'NEW' keyword?

    Quote Originally Posted by schoemr View Post
    John,

    Nothing is not a valid value for a reference type variable. A reference type variable is assigned a reference to an object OR it is assigned the special value null (the absence of an object reference)
    The absence of an object IS Nothing in VB. Try this code:
    VB.net Code:
    1. Dim var As Object
    2.  
    3. If var Is Nothing Then
    4.     Console.WriteLine("Looks like you owe someone an apology")
    5. End If

  5. #5
    Frenzied Member
    Join Date
    Apr 2016
    Posts
    1,415

    Re: Why do primitive types not require the 'NEW' keyword?

    Try this code:

    Code:
    Dim obj As Object
    
    Try
        obj = Nothing
    
    Catch ex As Exception
     Console.WriteLine("Error: " & ex.Message)
    End Try
    
    Console.WriteLine("You think?")

  6. #6
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,764

    Re: Why do primitive types not require the 'NEW' keyword?

    Quote Originally Posted by schoemr View Post
    Try this code:

    Code:
    Dim obj As Object
    
    Try
        obj = Nothing
    
    Catch ex As Exception
     Console.WriteLine("Error: " & ex.Message)
    End Try
    
    Console.WriteLine("You think?")
    Not sure the point of this.

    I'd look at https://learn.microsoft.com/en-us/do...eference-types

    and here https://learn.microsoft.com/en-us/do...erence/nothing you'll find this,

    If a variable is of a reference type, assigning Nothing to the variable sets it to a null reference of the variable's type. A variable that is set to a null reference is not associated with any object.
    So this statement,

    Nothing is not a valid value for a reference type variable.
    seems inaccurate.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  7. #7
    Frenzied Member
    Join Date
    Apr 2016
    Posts
    1,415

    Re: Why do primitive types not require the 'NEW' keyword?

    I'm sorry but I still think it is accurate:

    In Vb there are two kinds of data types: value types and reference types

    - Value types - hold a value directly
    - Reference types hold a reference to an object in memory.

    The keyword "Nothing" is used to represent the default value of a reference type, which is a null reference.

    When you assign the value "Nothing" to a reference type variable, it means that the variable does not refer to an instance of an object.

  8. #8
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,538

    Re: Why do primitive types not require the 'NEW' keyword?

    It's still a valid assignment ... it may not be a value, any more than null isn't also a value, but it's still a valid assignment. And rigtht, that variable no longer points to an instance, but it is still a valid assignment.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  9. #9
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,764

    Re: Why do primitive types not require the 'NEW' keyword?

    Quote Originally Posted by schoemr View Post
    I'm sorry but I still think it is accurate:
    What? Are you saying that this is accurate,

    Nothing is not a valid value for a reference type variable.
    Well despite what you think the documentation says otherwise, and in practice you can.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  10. #10

    Thread Starter
    Junior Member
    Join Date
    Jan 2022
    Posts
    26

    Re: Why do primitive types not require the 'NEW' keyword?

    Cool discussion. I don't really know the difference between reference types and value types - aside from passing arguments between functions, which i believe is the same/related principle.

    But I noticed I cannot do the following....

    Code:
    Dim MyString as New String
    Is it because the object is forcing me to call the constructor?

    Code:
                Dim MyStr As New String("mystring")  'success
    
                MyStr = "hello world"   '<--- so whats this now?
    It appears the above is assigning a value... but also initializing an object.

    Perhaps in VB you can set a 'default' value for an object that takes an assignment? I'm just a noob in OOP.

  11. #11
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,538

    Re: Why do primitive types not require the 'NEW' keyword?

    Quote Originally Posted by BitFlipper88 View Post
    Cool discussion. I don't really know the difference between reference types and value types - aside from passing arguments between functions, which i believe is the same/related principle.

    But I noticed I cannot do the following....

    Code:
    Dim MyString as New String
    Is it because the object is forcing me to call the constructor?
    Yes, when you use the New keyword, that invokes the constructor ... which happens to be a function .... SO, you need to call it with () at the end.
    Code:
    Dim MyString as New String() '<-- this works
    Code:
    Dim MyStr As New String("mystring")  'success
    MyStr = "hello world"   '<--- so whats this now?
    So what's happening here is that you're creating a string and initializing it to "mystring"
    The second then assigns the value "hello world" to it ... there's no magic behind it.
    I'ts the same as this:
    Code:
    dim MyString as String
    MyString = "mystring"
    MyString = "hello world"
    
    - or -
    dim MyString as String = "mystring"
    MyString = "hello world"
    
    - or -
    Dim X as Integer = 2
    X = 12
    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  12. #12
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Why do primitive types not require the 'NEW' keyword?

    Quote Originally Posted by schoemr View Post
    Try this code:

    Code:
    Dim obj As Object
    
    Try
        obj = Nothing
    
    Catch ex As Exception
     Console.WriteLine("Error: " & ex.Message)
    End Try
    
    Console.WriteLine("You think?")
    What the hell are you on about? Not that I needed to but I did just try that code and no exception was thrown, proving that assigning Nothing to a reference type variable is valid. If you were trying to prove that you were wrong, you succeeded spectacularly.

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Why do primitive types not require the 'NEW' keyword?

    Quote Originally Posted by schoemr View Post
    Nothing is not a valid value for a reference type variable.
    Quote Originally Posted by schoemr View Post
    The keyword "Nothing" is used to represent the default value of a reference type, which is a null reference.

    When you assign the value "Nothing" to a reference type variable, it means that the variable does not refer to an instance of an object.
    So it's not a valid value but it's the default value and it's a value you can assign?! Yeah, that makes perfect sense.
    Quote Originally Posted by schoemr View Post
    A reference type variable is assigned a reference to an object OR it is assigned the special value null (the absence of an object reference)
    Yeah, and that special value is represented by Nothing in VB, as you yourself pointed out in that later post.

    Maybe you could go back and reread post #2, then quote the specific part of that that you think is wrong and tell us exactly why. I've generally given up banging my head against this particular brick wall but I would like to ensure the OP here understands what is good information and what is bad, so they are not confused when writing their own code in the future.

  14. #14
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Why do primitive types not require the 'NEW' keyword?

    Quote Originally Posted by BitFlipper88 View Post
    Cool discussion. I don't really know the difference between reference types and value types - aside from passing arguments between functions, which i believe is the same/related principle.

    But I noticed I cannot do the following....

    Code:
    Dim MyString as New String
    Is it because the object is forcing me to call the constructor?

    Code:
                Dim MyStr As New String("mystring")  'success
    
                MyStr = "hello world"   '<--- so whats this now?
    It appears the above is assigning a value... but also initializing an object.

    Perhaps in VB you can set a 'default' value for an object that takes an assignment? I'm just a noob in OOP.
    Yes, the New keyword is used to invoke a constructor, which is a special method that constructs an instance of a type. Just like any other method, a constructor has a parameter list, which may be empty. Just like any other method, you can only call a constructor with arguments that match the parameters declared in the type. Here is the documentation for the list of constructors for the String class:

    https://learn.microsoft.com/en-au/do...r?view=net-7.0

    As you can see from that, there is no String constructor that has a single parameter of type String. That means that this:
    vb.net Code:
    1. Dim MyStr As New String("mystring")
    is not really valid. It will work if you have Option Strict Off but, if you mouse over the String keyword in that code you can see that the actual overload being invoked is the one with a Char array parameter. When you run that code, the String you pass in will be implicitly converted to a Char array and that will be passed to the constructor. If you turn Option Strict On, which you ALWAYS should, then that code will not compile and you'll be told that a String cannot be implicitly converted to a Char array.

    The reason that the String class has no constructor that takes a single String argument is, as I said before, String literals are supported. There's no need or point to this:
    vb.net Code:
    1. Dim MyStr As New String("mystring")
    when you can do this:
    vb.net Code:
    1. Dim MyStr As String = "mystring"
    You're using a String literal either way so why go through a constructor when you can simply assign directly?

    As I said previously, the reason you're getting confused here is that the String class appears to behave different to other classes and actually like a value type, but in actual fact that's simply because of literal support and immutability. String is a class and behaves like a class. If you do your testing with a class other than String, you'll see the difference because there will be no option to use literals of that type.

  15. #15
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,760

    Re: Why do primitive types not require the 'NEW' keyword?

    I've cleaned up this thread by removing several posts. JMcIlhinney/Schoemer please calm down.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  16. #16
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,600

    Re: Why do primitive types not require the 'NEW' keyword?

    I swear to God, it was a dark day when the concept of NULL was introduced to computer science. It's been a source of many sleepless nights....and many disagreements

    In any case, someone should have made sure to point out to the OP that the "New" operator is not essential to the instantiation of all objects all the time.

    Take this class for example:-
    Code:
    Public Class Person
    
        Public Property FirstName As String
        Public Property LastName As String
    
        Public Shared Widening Operator CType(ByVal s As String) As Person
            Dim a = s.Split(","c)
    
            Return New Person With {.FirstName = a(0), .LastName = a(1)}
        End Operator
    
    End Class
    The above class has it's CType operator overloaded such that it can be created directly from a String like this:-
    Code:
    Dim p As Person = "James,Holder"
    The above code instantiates a new Person object without the use of the New operator. Primitive types tend to behave the way they do because they tend to have many of their operators overloaded. Be careful when making assumptions about a type based on whether "New" is used or not. The "New" operator doesn't not actually tell you anything about a type. It doesn't tell you whether it's reference or value type and it doesn't tell you which, if any operators are overloaded.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width