Did you know if you are using DataSets throughout your application (not data readers) then you don't need to have any code about connection opening or closing.
Some say it is better to be explicit. However the bottom line is less code is less bugs.
try{cnn.Open();adapter.Fill(dataset);}catch (SQLException ex){MessageBox.Show(ex.Message);}finally{//I'm in the finally block so that I always get called even if the fill fails.cnn.Close();}
❌ Bad code: The connection code is not needed
try{adapter.Fill(dataset);}catch (SQLException ex){MessageBox.Show(ex.Message);}
✅ Good code: Letting the adapter worry about the connection
Note: A common comment for this rule is... "Please tell users to explicitly open and close connection - even when the .NET Framework can do for them"
The developers who prefer the first (more explicit) code example give the following reasons:
IDBCommand.ExecuteNonQuery() will throw an exception if the connection isn't open (it might be an interface method, but interface exceptions are documented as a strong guideline for all implementers to follow). The SqlCommand help doesn't mention anything further about this fact, but considering it's an inherited class, it would be fair to expect it to behave the same way. A number of the other methods don't make mention of connection state, making it difficult to know which basket to put your eggs into...Bottom line - It is a controversial one. People who agree with the rule include:
People who don't:
One final note: This argument is a waste of time... With code generators developing most of the Data Access layer of the application, the errors, if any, will be long gone and the developer is presented with higher level of abstraction that allows him/her to concentrate on more important things rather than mucking around with connections. Particularly considering that, when we start using the Provider model from Whidbey, it won't even be clear whether you're talking to SQL Server or to an XML file.