Reputation: 98
Firstly, am new to C# programming. I have created a dedicated class to get the connection string from the app.config of a Web Services application in Visual Studio 2010 as per the code below.
On building the code I get the following error via the catch block:
"The name 'connection' does not exist in the current context".
Obviously connection is going out of scope.
public class FCSConnection : IDisposable
{
public string GetDefaultConnectionString()
{
string DefaultConnectionString = null;
try
{
DefaultConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection connection = new SqlConnection(DefaultConnectionString);
connection.Open();
return DefaultConnectionString;
}
catch (Exception)
{
if (DefaultConnectionString != null)
{
connection.Dispose();
}
}
return DefaultConnectionString;
}
public void Dispose()
{
throw new NotImplementedException();
}
}
Upvotes: 2
Views: 821
Reputation: 100248
public class FCSConnection : IDisposable
{
private SqlConnection connection = null;
public string GetDefaultConnectionString()
{
string defaultConnectionString = null;
try
{
defaultConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
connection = new SqlConnection(defaultConnectionString);
connection.Open(); // are you sure want to keep the connection being opened??
}
catch
{
Dispose();
}
return defaultConnectionString;
}
public void Dispose()
{
if (connection != null)
{
connection.Dispose();
connection = null; // to avoid repeat dispose
}
}
}
Upvotes: 3
Reputation: 8667
The exact compiler message refers to your catch
statement:
connection.Dispose();
Here, connection
is an unknown name, because it's declared inside the try
block.
As for your entire code, I think it's also wrong. If you want your FCSConnection
class to encapsulate the SQL connection, you should declare connection
as a private member and then dispose it in your Dispose()
method.
Upvotes: 4