October 2nd, 2003, 04:29 AM
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["@BranchID"].Value = id;
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
//load object properties from data reader
catch (Exception ex)
throw new Exception(ex.Message);
October 2nd, 2003, 04:37 AM
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...
October 3rd, 2003, 05:24 PM
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.
Click Here to Expand Forum to Full Width
This a Codeguru.com survey!