| You are here: | About>Computing & Technology>Visual Basic> Using VB.NET> Coding New Instances of Objects |
![]() | Visual Basic |
Coding New Instances of ObjectsJun 26 2007 What's New about the New ConstructorOne of the first things that you learn about OOP is that you have to create a New instance before you use any dynamic object. ("Static" or Shared objects are different. To explore the differences between Shared an dynamic objects, see "Static" (that is, "Shared") versus Dynamic Types in VB.NET.) But what is the difference when you code ... Dim myObject as New myClass or Dim myObject as myClass = New myClass or Dim myObject as myClass The answer is ... nada, nichts, niente and nothing. To prove it let's try it in VB.NET 2005 Express. The most elementary way to code this is shown below. (Uncomment one of the options at a time). Module Module1 But the real resulting program is the MSIL (Microsoft Intermdediate Language) code that is created by the compiler. It's easy to take a look at this code using the ILDASM utility. If you're unfamiliar with ILDASM, read my article ILDASM and the .NET Framework Tools first. All three versions of object instantiation compile to exactly the same MSIL code. See the illustration below where the relevant display in ILDASM has been captured in Notepad. -------- So why are there three ways do to it? As far as I know, it's purely personal preference. I'm only familiar with one obscure reason for picking one style over the others. As it turns out, you can't enclose the instantiation in a Try-Catch block. But if you use the two line style, you can check the instantiation for errors. In other words, this doesn't work because the scope of newCust1 is limited to the Try-Catch block. Try But using the two statement style, you can do this: Dim newCust1 As Customer Actually, there is a fourth way to instantiate an object, called in-line instantiation, that is used quite a bit with objects that are only needed temporarily or as an argument to another function. If you read any of the GDI+ articles here at About Visual Basic, you saw this quite a bit. For example, in the first example code in that series ... Dim g As Graphics = e.Graphics ... the Font object is instantiated only for the purpose of passing it to the DrawString function. The code would work the same way if it was instantiated and assigned to a variable. Dim g As Graphics = e.Graphics |
Las Vegas on a BudgetFind a BargainHotel DealsCheap EatsFree AttractionsEntertainment for Less |
All Topics | Email Article | | | ![]() |
| Advertising Info | News & Events | Work at About | SiteMap | Reprints | Help | Our Story | Be a Guide |
| User Agreement | Ethics Policy | Patent Info. | Privacy Policy | ©2008 About, Inc., A part of The New York Times Company. All rights reserved. |


