0

this is my common app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="BO"
        connectionString="Data Source=MyServer;Initial Catalog=BO;User ID=WebUser;Password=xxxx"
        providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

And I'm working on a library, class.cs. Here's the part of the code where I get the error.

 public static SqlConnection getNewConnection()
        {
            string conection = ConfigurationManager.ConnectionStrings["BO"].ConnectionString.ToString();
            conn = new SqlConnection(conection);
            return conn;
        }

Error 1 The name 'conn' does not exist in the current context

Any idea? I have not copied any other file that's being referenced to the same file. (some error I've read is common when it comes to "does not exist in the current context")

Daniel Sh.
  • 2,078
  • 5
  • 42
  • 67
  • possible duplicate of [The name 'controlname' does not exist in the current context](http://stackoverflow.com/questions/706603/the-name-controlname-does-not-exist-in-the-current-context) – Ben Jun 19 '12 at 12:58
  • Looks like you are using an undeclared variable. – C.J. Jun 19 '12 at 13:00

3 Answers3

8

Where is conn declared ? Did you already declare it in an outer scope ? If not, declare it and you will be good.

Change this line

 conn = new SqlConnection(conection);

to

 SqlConnection conn = new SqlConnection(conection);

You can alternatively use implicit declaration using the var keyword. It is available from C# 3.0 onwards.

 var conn = new SqlConnection(conection);

The compiler will infer the type of the variable from the expression on the right side of the initialization statement

from msdn

An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

Shyju
  • 214,206
  • 104
  • 411
  • 497
3

change conn = new SqlConnection(conection); to var conn = new SqlConnection(conection);

2

Change:

conn = new SqlConnection(conection);

to:

SqlConnection conn = new SqlConnection(conection);

This should solve your problem, you need to define which type of object you are creating

arpz
  • 641
  • 5
  • 9