Results 1 to 14 of 14

Thread: Using New Keyword

  1. #1
    Hyperactive Member marniel647's Avatar
    Join Date
    Aug 10
    Location
    MSDN Library
    Posts
    256

    Using New Keyword

    Hi guys i'm just having a question in my mind why do we use New keyword when declaring a variable.
    I read about the new keyword but i think i need a better understanding about that keyword. I already now that it will create an instance of the class

    Why do we need to use New keyword in some of a object type variable.

    also what is the difference with this

    Code:
    Dim Button1 As System.Windows.Forms.Button
    Dim Button2 As New System.Windows.Forms.Button()
    Sorry for the noob question but i want to clarify my understanding
    Thanks

  2. #2
    Lively Member elielCT's Avatar
    Join Date
    Jun 11
    Posts
    77

    Re: Using New Keyword

    Code:
    Dim Button1 As System.Windows.Forms.Button
    here your trying to use the actual object of button in the System.Windows.Forms. This should be used as the actual definition by which you would use to create a button. So you can't use the actual model for buttons.

    Lets say if you did, then you would actually be using the actual button in the .net library. Not your own.

    So you use the new keyword to make a copy (with all its properties and methods) and now you can use it as your own..

    I think a good example would be if you create a dataset in your project. If you reference that dataset without using new, that dataset will hold the data you put in it. So everytime i call that dataset it will have whatever was put into it. But if i were to use new, when the sub exits (assuming i called new inside a sub), and i reference the dataset, its empty..

    So if you make a definition for Human, assign properties (has 2 arms, legs, ect..) and methods (can run, talk, ect..) someone would need to create a New human instance, give it a Name, and specify unique atributes.. They cant just go in and reference the actual Human model!

    Maybe i wasnt the best one to explain this..

  3. #3
    Frenzied Member MattP's Avatar
    Join Date
    Dec 08
    Location
    WY
    Posts
    1,182

    Re: Using New Keyword

    Your first statement creates a variable that can contain a reference to a Button. At this point Button1 will have the value of Nothing because you haven't assigned a Button to it.

    The second statement does the same thing as the first one with one difference. The New keyword creates a Button and assigns it to the variable.
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  4. #4
    PowerPoster techgnome's Avatar
    Join Date
    May 02
    Posts
    21,636

    Re: Using New Keyword

    when ever you Dim something as an object, basically you're telling VB "I need a box" ... but it doesn't create the box. When you new the object (be it at the moment of declaration or later) then that tells VB "Ok, go make me my box" ....


    elielCT's post has some stuff ok, but some of it is misinformation....

    :here your trying to use the actual object of button in the System.Windows.Forms. This should be used as the actual definition by which you would use to create a button. So you can't use the actual model for buttons. " -- There's nothing wrong with that... if you look at the .Designer code of any form, you'll find this is exactly how every button and object on a form is declared and created.

    "Lets say if you did, then you would actually be using the actual button in the .net library. Not your own." -- true... but what you're using is your INSTANCE of that button... which you could then add to your form, change the caption on, size, etc.

    "So you use the new keyword to make a copy (with all its properties and methods) and now you can use it as your own.." -- I refer to the previous comment about instances.

    "I think a good example would be if you create a dataset in your project. If you reference that dataset without using new, that dataset will hold the data you put in it. So everytime i call that dataset it will have whatever was put into it." -- Ah... no... again, all you have done is tell VB, hey I need a box that looks like a Dataset... the dataset still does not exist... so it's not going to hold any data
    "But if i were to use new, when the sub exits (assuming i called new inside a sub), and i reference the dataset, its empty.." -- Correct, you've told VB to go create your box, so that is now what you have, an empty box.

    Now... if you create a typed dataset, you still would need to dim and new it... that's how it gets the data you put into it (which isn't accurate either, as it's connected to a data source that contains the data. The reason you don't need to dim and new the dataset is because it's handled behind the scenes for you automatically and the IDE gives you a shared class that allows you access it directly.

    "So if you make a definition for Human, assign properties (has 2 arms, legs, ect..) and methods (can run, talk, ect..) someone would need to create a New human instance, give it a Name, and specify unique atributes.. They cant just go in and reference the actual Human model!" -- Now that's correct.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    *Proof positive that searching the forums does work: View Thread *
    * 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??? *
    * Use Offensive Programming, not Defensive Programming. * On Error Resume Next is error ignoring, not error handling(tm).
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN

  5. #5
    Lively Member elielCT's Avatar
    Join Date
    Jun 11
    Posts
    77

    Re: Using New Keyword

    Ah... no... again, all you have done is tell VB, hey I need a box that looks like a Dataset... the dataset still does not exist... so it's not going to hold any data
    disagree, because i actually reference the actual dataset i created via the wizard, to store my data so i dont need to reference the database for the same info over and over.. I put data, and the data stays, i never created a new instance, im working with the same instance created via the wizard.. Which is a new instance of the dataset object, but i was referring to using that instance, rather than declaring a new instance.. Its was intended for a basic idea..

    If i wouldve used new, it would have the tables i created in it, but the data would be empty...

    Whereas calling it directly, it retains the data...

    I forgot to mention the dataset isnt declared on the fly.. Its part of the project... Just as you would put a form in your project, as opposed to creating it on the fly with code in your project...

    and if you look at the source for the designer, where the form objects are declared, each has a new instance, assigned a name, then properties which are read/write are assigned values...

  6. #6
    PowerPoster techgnome's Avatar
    Join Date
    May 02
    Posts
    21,636

    Re: Using New Keyword

    Yeah, I got that.... and that's what I was saying.... the creation of the dataset is done behind the scenes... it's not magic... just a black box. And it works the way it does because it creates the instance for you then sets the shared dataset to that instance, giving it the appearance of "just being" there. That's also why I made the distinction between a Dataset and a typed Dataset (which is the behavior you're describing) ... Even still if you
    Dim myDataset as someTypedDataset ... where someTypedDataset is a dataset you created through the wizard ... it still won't actually create it... it's still just you telling VB "Hey, I need a box" ... you still have to instanciate it, and you still need to fill it.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    *Proof positive that searching the forums does work: View Thread *
    * 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??? *
    * Use Offensive Programming, not Defensive Programming. * On Error Resume Next is error ignoring, not error handling(tm).
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN

  7. #7
    Lively Member elielCT's Avatar
    Join Date
    Jun 11
    Posts
    77

    Re: Using New Keyword

    yea... i meant to use an example, I shouldve made my self clear about it being part of the solution...

    that way the distinction between using an object already in existence vs instantiating a new instance..
    & maybe it would make more sense why you dont directly use an object, but rather create a copy and use that instead...

  8. #8
    Loquacious User Shaggy Hiker's Avatar
    Join Date
    Aug 02
    Location
    Idaho
    Posts
    20,390

    Re: Using New Keyword

    That's still not right. The object doesn't exist until somebody creates an instance of it. There are a few types of objects, such as forms, where MS has created default instances of them, so that the instance is created for you and it looks like it was always there. Another type of object where that appears to be the case is objects that implmenet the Singleton pattern where you have a Shared instance accessible through a private constructor such that it looks like it was always there. It isn't though, it just has a private constructor and an accessor that creates the instance the first time you try to access it. Those are kind of rare, though.

    In all classes, you have a definition of the class, which defines the members, constructors, properties, events, methods, and so forth. That defines the object. In every single case, somebody has to explicitly create an instance of the object before it can be used. There are ways to fool people into thinking that an instance was already there and didn't have to be created, but that is all just smoke and mirrors. Every object has to be created with New before it can be used, though you may not always see the use of the New keyword because something could have been done to hide it from you.

    Every object has to be instantiated before it is used. You aren't making copies unless you explicitly call a Copy or Clone method. All you are doing is creating instances of the object.
    My usual boring signature: Nothing

  9. #9
    Lively Member elielCT's Avatar
    Join Date
    Jun 11
    Posts
    77

    Re: Using New Keyword

    when you instantiate something your making a copy.. plain and simple..

    no need to over complicate it...

    not making a copy in the same sense as a copy command.. nobody is talking about that...

    It was an example to illustrate an idea...

    If you add something to your solution, it instantiates or makes a copy for you...

    If i have two forms in my solution.. I can still create a new instance of another from the first..... assign it a name..
    But you dont have to..

    I can do form2.show
    or dim tot as new form2
    tot.show..

    When you start programming101 they dont frickin break it down to an atomic level.. and over complicate ****..
    You get a general idea for your understanding... Then you get into the inner working...

    The best way to understand something is through comparison and through analogies...

    if you think you have a better example then by all means... everyone explains thing slightly different..

    but nit picking someone elses example isnt helping anything.. especially not the original posters question...


    if you dont make a new COPY of form2 you are affecting form2... If you make a copy the original isnt touched...

  10. #10
    PowerPoster techgnome's Avatar
    Join Date
    May 02
    Posts
    21,636

    Re: Using New Keyword

    simple examples are one thing... mis-information is another... the problem is that all too often around here, we see people with a little bit of information becoming dangerous because they don't completely understand the inner workings.

    Let's take your Form2 example... this is a classic example of when good intentions go bad... and I put most of the blame on VB for this because it has something that no other language has: default form instances... and not understanding how they work can lead to some dire consequences.

    Try this out... start a new project... give it two forms, Form1 and Form2. In the properties of Form2, set the Text property to "This is Form2" ... now add a button to Form1, and add this code:
    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Form2.Text = "New Caption"
    
            Dim myForm As New Form2
            Form2.Show()
            myForm.Show()
    
        End Sub
    Now you can see the first line modifies Form2... by changing the caption... and then I create a new instance of Form2 ... but what happens when the forms are shown? Their captions are different. That's because I didn't change Form2 at all ... what I changed was VB's Default Instance of that form. Behind the scenes, an instance of Form2 was created, and it was then returned back as the Default instance of that form. I didn't create it, VB takes care of that. The same thing is happening with the typed dataset... it's just ticked away in the designer code.

    now change the code above to this:
    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Form2.Text = "New Caption"
    
            Dim myForm As New Form2
    
            myForm = Form2
    
            Form2.Show()
            myForm.Show()
    
        End Sub
    What happened this time? Only one form showed up... and it had the "New Caption" ... that's because I set myForm equal to the default instance.. so now they are one in the same... two variables pointing to the same instance.


    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Form2.Text = "New Caption"
    
            Dim myForm As New Form2
    
            myForm = Form2
    
            Form2.Text = "And another cpation"
    
            Form2.Show()
            myForm.Show()
    
        End Sub
    Same thing again... one form... with the "And another caption" title.

    yeah, sure programming 101 doesn't break it down to the atomic level... but perhaps they should. And yes, analogies and comparisons are good, I use eggs, cars, and boxes a lot. But you have to make sure that the analogies are correct. I tried to be as simple as I could in my initial reply to the OP... the difference is that one says "I need a box" and the other says "I need a box, go make it for me" .... pure and simple. OK, so maybe I'm in the wrong for trying to set the record straight in your post. If it'll make you happy, I'll simply ignore any further posts from you. But I'll leave you with this, it scares me to death sometimes some of the misinformation I see out there... someday, one of these guys is going to be programming my pacemaker... I want to make dog dang sure that who ever does that, gets it right. there will be no staging environment. There will be no testing environment. So any chance I get to set some one straight, you're dang right I'll take advantage of the situation.

    If everyone started programming like their life depended on it, we would probably see a huge increase in bug free software.
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    *Proof positive that searching the forums does work: View Thread *
    * 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??? *
    * Use Offensive Programming, not Defensive Programming. * On Error Resume Next is error ignoring, not error handling(tm).
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN

  11. #11
    Hyperactive Member marniel647's Avatar
    Join Date
    Aug 10
    Location
    MSDN Library
    Posts
    256

    Re: Using New Keyword

    Quote Originally Posted by Shaggy Hiker View Post
    That's still not right. The object doesn't exist until somebody creates an instance of it. There are a few types of objects, such as forms, where MS has created default instances of them, so that the instance is created for you and it looks like it was always there. Another type of object where that appears to be the case is objects that implmenet the Singleton pattern where you have a Shared instance accessible through a private constructor such that it looks like it was always there. It isn't though, it just has a private constructor and an accessor that creates the instance the first time you try to access it. Those are kind of rare, though.

    In all classes, you have a definition of the class, which defines the members, constructors, properties, events, methods, and so forth. That defines the object. In every single case, somebody has to explicitly create an instance of the object before it can be used. There are ways to fool people into thinking that an instance was already there and didn't have to be created, but that is all just smoke and mirrors. Every object has to be created with New before it can be used, though you may not always see the use of the New keyword because something could have been done to hide it from you.

    Every object has to be instantiated before it is used. You aren't making copies unless you explicitly call a Copy or Clone method. All you are doing is creating instances of the object.
    Quote Originally Posted by techgnome View Post
    simple examples are one thing... mis-information is another... the problem is that all too often around here, we see people with a little bit of information becoming dangerous because they don't completely understand the inner workings.

    Let's take your Form2 example... this is a classic example of when good intentions go bad... and I put most of the blame on VB for this because it has something that no other language has: default form instances... and not understanding how they work can lead to some dire consequences.

    Try this out... start a new project... give it two forms, Form1 and Form2. In the properties of Form2, set the Text property to "This is Form2" ... now add a button to Form1, and add this code:
    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Form2.Text = "New Caption"
    
            Dim myForm As New Form2
            Form2.Show()
            myForm.Show()
    
        End Sub
    Now you can see the first line modifies Form2... by changing the caption... and then I create a new instance of Form2 ... but what happens when the forms are shown? Their captions are different. That's because I didn't change Form2 at all ... what I changed was VB's Default Instance of that form. Behind the scenes, an instance of Form2 was created, and it was then returned back as the Default instance of that form. I didn't create it, VB takes care of that. The same thing is happening with the typed dataset... it's just ticked away in the designer code.

    now change the code above to this:
    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Form2.Text = "New Caption"
    
            Dim myForm As New Form2
    
            myForm = Form2
    
            Form2.Show()
            myForm.Show()
    
        End Sub
    What happened this time? Only one form showed up... and it had the "New Caption" ... that's because I set myForm equal to the default instance.. so now they are one in the same... two variables pointing to the same instance.


    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Form2.Text = "New Caption"
    
            Dim myForm As New Form2
    
            myForm = Form2
    
            Form2.Text = "And another cpation"
    
            Form2.Show()
            myForm.Show()
    
        End Sub
    Same thing again... one form... with the "And another caption" title.

    yeah, sure programming 101 doesn't break it down to the atomic level... but perhaps they should. And yes, analogies and comparisons are good, I use eggs, cars, and boxes a lot. But you have to make sure that the analogies are correct. I tried to be as simple as I could in my initial reply to the OP... the difference is that one says "I need a box" and the other says "I need a box, go make it for me" .... pure and simple. OK, so maybe I'm in the wrong for trying to set the record straight in your post. If it'll make you happy, I'll simply ignore any further posts from you. But I'll leave you with this, it scares me to death sometimes some of the misinformation I see out there... someday, one of these guys is going to be programming my pacemaker... I want to make dog dang sure that who ever does that, gets it right. there will be no staging environment. There will be no testing environment. So any chance I get to set some one straight, you're dang right I'll take advantage of the situation.

    If everyone started programming like their life depended on it, we would probably see a huge increase in bug free software.
    Thanks for all the help Guys actually i'm waiting for Jmc to post a better explanation to me about this keyword because i think he can explain it better without reading it so many times by the way thank you all guys.

    I think this 2 post will lead to better understanding to me using the New keyword.

  12. #12
    PowerPoster techgnome's Avatar
    Join Date
    May 02
    Posts
    21,636

    Re: Using New Keyword

    Then I don't know what to tell you... I thought it was pretty clear. Dimming an object says "I need a box" ... but does not actually create the box. "Newing" an object actually creates an instance of that object (ie, it creates the box) ...

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    *Proof positive that searching the forums does work: View Thread *
    * 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??? *
    * Use Offensive Programming, not Defensive Programming. * On Error Resume Next is error ignoring, not error handling(tm).
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN

  13. #13
    Frenzied Member Evil_Giraffe's Avatar
    Join Date
    Aug 02
    Location
    Suffolk, UK
    Posts
    1,876

    Re: Using New Keyword

    Quote Originally Posted by marniel647 View Post
    Thanks for all the help Guys actually i'm waiting for Jmc to post a better explanation to me about this keyword because i think he can explain it better without reading it so many times by the way thank you all guys.
    I'm not quite sure what you're after in terms of an explanation that hasn't been given already. You actually nailed the use of the keyword in your first post:

    Quote Originally Posted by marniel647 View Post
    I already [k]now that it will create an instance of the class
    If you're having further issues understanding this, you don't need further explanation of the New keyword, you need to solidify your understanding of variables, classes and instances.

  14. #14
    Loquacious User Shaggy Hiker's Avatar
    Join Date
    Aug 02
    Location
    Idaho
    Posts
    20,390

    Re: Using New Keyword

    Quote Originally Posted by elielCT View Post
    when you instantiate something your making a copy.. plain and simple..

    no need to over complicate it...

    not making a copy in the same sense as a copy command.. nobody is talking about that...
    I agree with you up to a point. The word copy can certainly be used the way you are using it, because an instance could be seen as a copy. However, the more common use of copy in programming is much more involved, potentially. Copying value types is trivial, but copying reference types, such as forms, as TG showed, is much more involved. While you could use the term copy to mean instance, I would suggest that if such a mental model takes root it will lead to confusion down the road when you try to copy reference types and find out that it is considerably more involved. It's just a matter of words, which often have multiple meanings. I would prefer to reserve the word Copy to true copy situations, and use the word instance to indicate instances.
    My usual boring signature: Nothing

Posting Permissions

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