2

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.

  1. How do I avoid this error?
  2. Is the Dispose method being used correctly here?

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();
    }        
}
4
  • 4
    I'm tempted to downvote this, you should know what scope means. Anyway, the scope of connection is only the try block. Commented May 19, 2011 at 10:31
  • 4
    @Bobby, did you read the line "am new to C# programming"? Learning about scope, especially with try/catch blocks, is something everyone goes through. Commented May 19, 2011 at 10:36
  • 1
    Intellisense of VS 2010 helps you a lot and a beginner can also avoid such errors using it. Spend some time on learning. Commented May 19, 2011 at 10:40
  • @StuperUser: Yes, but it is a very basic concept you should grasp right from the beginning, especially with Object-Oriented languages. Trial & Error using the IDEs (if any) AutoCompletion-Feature is also a very simple why to figure that out I can use DefaultConnectionString in there, but not connection, what's the difference between the two?. But you're right, my comment sounds a little bit more harsh then meant to. Commented May 19, 2011 at 10:41

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3
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
        }
    }        
}

6 Comments

That'll definitely do the trick, but you only need to call Dispose on connection; that'll take care of closing the connection if it's already open. It might also be worth setting the connection to null after it has been disposed in case someone calls Dispose on FCSConnection more than once - that's less important in this case though.
+1 for your comment //are you sure want to keep the connection being opened??, the connection isn't accessible to classes outside. Maybe renaming the method to GetDefaultConnection and return connection? Would solve that issue?
@bombus17: Glad it helped! Consider the comments of @Mike and @StuperUser. Also don't forget to accept the correct answer using green tick to the left.
I'm tempted not to comment, as to avoid sounding nit-picking. But since to OP is new to C#, I think that a catch-all block is quite something you want to avoid. You might very well know that it catches basically everything (including native-induced access violations, etc.), but newbies my not. Personally, I think such things should never be used, be it in samples or "real code". YMMV of course.
@Christian: Swallowing of exception if very bad practice. My goal was to show how the same code can be written better. Saying to a newbie "all you're doing is wrong, don't do this, do that instead" brings no unpedagogic sense :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.