CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2003

    Constructor to cancel object creation


    I have a constructor like the one below that searches the DB for a company with the id and fills the object properties if the record is found. The problem is that if the record is not found the object is still created with empty properties. I want to change this so that if no company is found the object is not created at all.

    Also, if a null value(for example) is returned when the company is not found how would I handle this from my calling code?

    Any help would be great.


    public Company(int id)
    SqlConnection conn = new SqlConnection(ConnString);
    SqlCommand cmd = new SqlCommand("Select * from Company_Branch where BranchID = @BranchID",conn);
    cmd.Connection = conn;
    cmd.Parameters.Add(new SqlParameter("@BranchID",DbType.Int16));
    cmd.Parameters["@BranchID"].Value = id;
    SqlDataReader dr = null;
    dr = cmd.ExecuteReader();
    if (dr.Read())
    //load object properties from data reader
    catch (Exception ex)
    throw new Exception(ex.Message);

  2. #2
    Join Date
    Dec 2000
    Throw an exception even if you don't find the row you are searching for... Catch the exception in the caller function and handle it there... And the just forget created object. It will be deleted by GC...


  3. #3
    Join Date
    Oct 2003

    I would imagine that you may want to add a property to your class. Let's just call it "status". Within your constructor
    set the value of the property based on the success or failure of trying to locate the id within your database. After creating an instance of your class within the calling code, immediately test the status property of your object. If it failed then you know which route to go in your calling code.

    As for destroying the instance. C# garbage collection should handle your unused objects. However, I would imagine that
    you are probably going to be using the same object reference for new instances of Company class. In that case the moment you declare a new company using the same object reference, the old will be immediately destroyed.
    I never said my answer was the right one; just a different way to look at things.

Posting Permissions

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

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.