Sponsored Ad

Saturday, September 26, 2009

C# Using

using in C# can be used in two ways:
  • as a shortcut to typing long namespaces used in code
  • as a means of properly and automatically close and dispose any object references implementing the IDisposable interface
For the latter, here's an example, in which a clandestine abettor adjustment allotment a DataSet object. I about address abstracts admission cipher wherein abstracts is pulled from a SQL Server database through a stored action aural a library like so:


using System.Data;
using System.Data.SqlClient;
private DataSet GetFreshData(string sprocName)
{    
using ( SqlConnection conn = new SqlConnection() )    
{    
using ( SqlDataAdapter da = new SqlDataAdapter() )
{                
da.SelectCommand = new SqlCommand();    
da.SelectCommand.CommandText = sprocName;    
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Connection = conn;        
DataSet ds = new DataSet();      
try        
{      
da.SelectCommand.Connection.Open();
da.Fill(ds);    
da.SelectCommand.Connection.Close();  
}          
catch  
{          
return null;        
}        
finally  
{        
// do other things...calling Close() or Dispose()  
// for SqlConnection or SqlDataAdapter objects not necessary  
// as its taken care of in the nested "using" statements
}
return ds;  
}
}
}

0 comments:

Post a Comment

Sponsored Ad

More Related Articles

Website Update

Followers