?
Solved

Concept Clarification:  Constructors

Posted on 2005-03-17
3
Medium Priority
?
423 Views
Last Modified: 2010-04-16
My previous programming experience has been in the use of Visual Basic 6.0.  I purchased two books on C# to try to learn how to use it.  One of the concepts that I am having trouble understanding is the use of constructors.  How they are used and what benefits they offer.  Can any offer some explanation and/or some simple code explaining this?

Thank you,
Kevin
0
Comment
Question by:kmcbrearty
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 1

Accepted Solution

by:
Pankaj27 earned 1000 total points
ID: 13568738
Constructors are used for initializing various entities associated with the object. Whenever a object is instantiated a constructor is called. constructor does not have a return type. Whenever you create a class in C# you will see a constructor in the .cs file. In VB6 which you are familiar with, a constructor for the object is created but that code is not accessible to the user.

egs of using a constructor
1) You can initialize your database connection in a constructor.
2) All the variables of your class can be set in constructor.

Constructors can be overloaded. When you say

Class 1 obj1 = new Class1();

This is a call to default constructor.

But you can have n numbers of constructors.

e.g.

Class 1 obj1 = new Class1(string);

In this case you have to define a constructor which takes one parameter of type string. This can be used to set a object variable with the value read in the by the string variable.

Let me know if any more questions need to be answered.

Pankaj
0
 
LVL 3

Author Comment

by:kmcbrearty
ID: 13571439
Based on your response I have two additional questions.  First you mentioned you can use a constructor to initialize a database connection.  This is a very interesting option for me, and it sounds like this is something you have done in the past.  Do you happen to have a basic implementation of this that you could possibly post.  Second, based on what I have read am I correct in saying that you don't have to use a constructor.

Thank you for your input,
Kevin
0
 
LVL 7

Assisted Solution

by:NipNFriar_Tuck
NipNFriar_Tuck earned 1000 total points
ID: 13576296
Kevin, basically the constructor is used to initialize your class...  They can be overloaded i.e. You could in one initialize a db connection and in another open a file stream or whateve else that you want.  This is basically what Pankaj said.

As to if you have to use a constructor or not, that is a missleading question... more appropriately would be do you have to implement a constructor?  The answer is no you do not, in C# every class has an implecit constructor with no arguments and when you instantiate the class in your code that default constructor is called automagically.  However, if you do create a constructo with arguments then if you want a constructor with no arguments you must explicitly create it.


As to creating a db connection on class connection...

public class MyDbClass : object, IDisposable
{
   private IDbConnection dbConn = null;
   private bool bDisposed = false;

   public MyClass( string conStr ) {
      dbConn = new System.Data.SqlClient.SqlConnection( conStr );
   }

   ~MyClass() {
      Dispose( false );
   }

   public void Dispose() {
      GC.SuppressFinalize( this );
      Dispose( true );
   }

   protected void Dispose( bool bDisposing ) {
         lock ( this ) {
            if ( bDisposing && !bDisposed ) {
            try {
               if ( dbConn != null ) {
                  dbConn.Dispose();
               }
            }
            catch ( Exception ex ) {
            }
         }
      }
   }  
}

This is a basic implementation of a db class that creates a connection on instantiation.  It also implements a dispose pattern, which I would recomend any time that you use a resource in a class as there are a number of resource classes that do not clean up correctly unless their dispose method is called.  For instance it is possible to loose connection to the data base if the connection class is allowed to just fall out of scope....  Also by implementing the IDisposable interface you can use this clase like...

using ( MyDbClass dbClass = new MyDbClass( myConStr ) ) {
}

and the dispose method will be called automagically when the code leaves the block of code the using statement is encompasing.

HTH...
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question