Concept Clarification: Constructors

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
LVL 3
kmcbreartyAsked:
Who is Participating?
 
Pankaj27Connect With a Mentor Commented:
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
 
kmcbreartyAuthor Commented:
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
 
NipNFriar_TuckConnect With a Mentor Commented:
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
All Courses

From novice to tech pro — start learning today.