7 Steps to Recover a Failing ProjectLink Round-Up for 9/13/07

Introduction to Constructors and Destructors in VB.NET

September 12th, 2007

You don't need a hard hat to construct objects in VB.NETProgrammers moving from VB6 into VB.NET and more object oriented programming in general often wonder about how to use the constructor method (New) and the destructor method (Finalize). I’ve seen questions on this topic come up from time to time in VB related discussion forums. Constructors/Destructors of a sort were in VB6, using the names Initialize and Terminate. However, they could not take parameters and were otherwise limited in what they could do so few programmers used them. In VB.NET, the constructors and destructors are much more powerful. In this article, we’ll look at some ways to use them.

New - The Constructor

In OOP a constructor is a function that has the task of initializing the object. In VB.NET, this is defined as a Sub with the name of New. It’s called whenever an object is created using the New statement, like so:

Dim MyProduct As New Product

This isn’t that different from initializing an object in VB6. However, in .NET we can pass data to the constructor so we could have something like this:

Dim MyProduct As New Product(ProductDataRow)

In our first example, the initialization is handled entirely within the object. It might load default variables internally or just do nothing at all. It might look something like this

Public Sub New()
    _iD = 0
    _description = String.Empty
    'other variable init goes here
End Sub

If you don’t include a constructor routine in your code, the VB.NET compiler creates one like this for you, except that it doesn’t contain any variable initialization code. However, if you have a New routine with a parameter in your class, no default empty New routine will be created. In that case, you’ll need to create an empty one yourself. Having this no argument constructor is important when you want to use inheritance so it’s usually a good idea to code one. If you don’t want it to be called other than by an inheriting object, use the Protected access modifier for it.

In our second example, we’re send in a DataRow to initialize the object so the code would look something like this:

Public Sub New(ByVal productData As DataRow)
    _iD = CInt(productData.Item("ProductID"))
    _description = productData.Item("Description").ToString
    'other variable init goes here
End Sub

Now, what really can throw some VB6′ers at first is that both these functions can be in the same class so that you can have multiple constructors in a class. As long as each version of the New routine has a different set of parameters, you can define as many constructors as you want or need. I’ve generally found 6-8 to be a good maximum number of overloaded New methods. Much more than that could indicate design problems although there can be exceptional cases.

As I noted above, you can also control how and when an object is created by using access modifiers. For example, you could make one New method public, such as passing in a datarow, and another private, such as passing in a private object unique to your program as seen here:

Public Sub New()
    'Does Nothing
End Sub

Public Sub New(ByVal productData As DataRow)
    'Intializes object from datarow
End Sub

Private Sub New(ByVal productData As DataRow, ByVal secretStuff As SecretSauce)
    'Intializes object from datarow plus 'SecretSauce' object
End Sub

You can also use private constructors to create a Singleton class pattern by preventing a caller from directly instantiating an object. I’ll be discussing this pattern in an upcoming article.

One thing to keep in mind with your New routines is to keep the code as short as possible here. Lengthy initializations may indicate a design problem with your class, such as it being too complex or bloated. Avoid the temptation of doing everything with this routine. Instead, create additional methods for functionality beyond the basic initialization.

Finalize - The Destructor

The destructor is the last method run by a class. This is called Finalize in VB.NET and it’s called whenever the .NET runtime is told directly or otherwise determines that an object is no longer required. Common uses for the Finalize method is to decrement or increment counters or release resources.

The VB.NET compiler creates a default Finalize method that, behind the scenes, will release variables. However, there may be cases where it’s preferable to have your own code in this routine. When you do this, you have to use the Overrides keyword in your declaration, like so:

Protected Overrides Sub Finalize()

Note that you can’t add parameters to this routine and you can’t use a difference access level than Protected.

One thing to bear in with with Finalize is that there is no set time when this method will be called. Garbage collection, the final release of objects in memory, in the .NET Framework is nondeterministic. Therefore, you should use care when releasing unmanaged objects or calling other classes or components from this routine. You might get unexpected results.

Like the New method, you should also limit the amount of code you put in this routine. My take on it is to simply use the default, compiler built, Finalize unless there is a strong need to perform an action when the object is being destroyed.

I hope this introduction to the way VB.NET uses constructors and destructors has been helpful to you, particularly if you’re migrating to VB.NET from VB6. Let me know what you think or if you have any questions by leaving a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: VB.NET Tutorials, VB6 To VB.NET


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (19 votes, average: 3.89 out of 5)
Loading ... Loading ...

11 Comments Add your own

  • 1. links for 2007-09-13 &laq&hellip  |  September 13th, 2007 at 10:21 am

    [...] Introduction to Constructors and Destructors in VB.NET (tags: dotnet) [...]

  • 2. reyad  |  October 24th, 2007 at 3:26 pm

    thank you so much ,, i been looking since hours at some website that explains to me the “constructor”
    thank alot .

  • 3. jfrankcarr  |  October 24th, 2007 at 3:51 pm

    Thanks for stopping by Reyad. I’m glad my article helped you out.

  • 4. Haroon  |  September 17th, 2008 at 10:18 am

    Please post a simple example code for this

  • 5. Haroon  |  September 17th, 2008 at 10:21 am

    Please post a small sample code to elaborate it. especially for destructor

  • 6. midhat  |  October 8th, 2008 at 12:06 am

    Thanks so much.This is very helpful article. It helps me out alot.

  • 7. suresh  |  October 15th, 2008 at 2:18 am

    can u send simple simple example code for constructor in vb .net

  • 8. Mike Robbins  |  July 6th, 2009 at 10:16 am

    Great information very useful

  • 9. yona  |  July 9th, 2009 at 7:35 am

    Please add a simple example for destructor method

  • 10. Gokul  |  August 24th, 2009 at 6:38 am

    Send Sample code using constructor in vb.net

  • 11. Kevin  |  November 20th, 2009 at 3:24 pm

    I come froma C/C++ background. Constructors and deconstructers are common in OO languages.

    Deconstructors are generally used to clean up memory - like releasing a variable from memory - or closing a database connection. In some langauges like objc on the iPhone the deconstructor is used a lot since you have to do your own memory management.

    A common way of using constructors is to have them nested providing default values for for other constructors. However, for most people in VB you will use optional parameters instead of the following example. Optional parameters aren’t usually available in other languages so this is how it is handled.

    Public Sub New()
    Me.New(”Category 1″)
    End Sub

    Public Sub New(category as String)
    Me.New(category, 1))
    End Sub

    Public Sub New(category as String, level as Integer)
    m_Category = strCat
    m_Level = level
    End Sub

    There might be certain cases with VB to do the above. But most likely you will do a Public Sub New(Optional category as String = “Category 1″, Optional level as Integer = 1)

    Note: The author mentioned this but I will explain it in a little more detail. You cannot have the following two constructors
    Public Sub New(category as String, level as Integer)
    Public Sub New(name as String, ID as Integer)

    You cannot have constructors with the same signature, in this case two parameters where the first is a string and the second is an integer. The compiler won’t know which one to use if you do a Dim myVar as New MyClass(”Me”, 1).

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives