Reputation: 2472
Last time I had a similar question, but we figured out if initialize and set a value for the variable before the logic statement then I can use the value that was generated within the logic statement.
This time, I want to call one of two method overloads depending on if the connection string is empty or not. Like so.
if (ConnectionString != "") // if there is something in the config file work with it
{
SqlConnection dataConnection = new SqlConnection(ConnectionString);
}
else
{
SqlConnection dataConnection = new SqlConnection();
}
try {
// ...
The problem is that anything in the try block fails because it does not know about the dataConnection.
How can do I do this in a way to make it work?
Upvotes: 1
Views: 1151
Reputation: 74166
You can do it like this:
SqlConnection dataConnection = !string.IsNullOrEmpty(ConnectionString)
? new SqlConnection(ConnectionString) : new SqlConnection();
Or:
SqlConnection dataConnection;
if (string.IsNullOrEmpty(ConnectionString))
{
dataConnection = new SqlConnection(ConnectionString);
}
else
{
dataConnection = new SqlConnection();
}
Upvotes: 5
Reputation: 1063338
Declare it (uninitialized) outside:
SqlConnection conn;
if(string.IsNullOrEmpty(connectionString)) {
conn = new SqlConnection();
} else {
conn = new SqlConnection(connectionString);
}
If the logic is simple, a conditional is possible too:
SqlConnection conn = string.IsNullOrEmpty(connectionString)
? new SqlConnection() : new SqlConnection(connectionString);
The latter is much easier to use with a using
block, as it can be done inline.
Upvotes: 3
Reputation: 237
You can declare the variable with null value out side the if statment and then use it inside the if statment and when you need to use it check if it's not null
SqlConnection dataConnection = null;
if (ConnectionString != "") // if there is something in the config file work with it
{
dataConnection = new SqlConnection(ConnectionString);
}
else
{
dataConnection = new SqlConnection();
}
try
{
if(dataConnection != null)
DoWhatYouWant();
}
Upvotes: 1
Reputation: 62835
I think you should define connection before if statements
SqlConnection dataConnection = null;
if (ConnectionString != "") // if there is something in the config file work with it
{
dataConnection = new SqlConnection(ConnectionString);
}
else
{
dataConnection = new SqlConnection();
}
try
{
Upvotes: 1
Reputation: 81645
You have to have the variable outside the if block:
SqlConnection dataConnection;
if (ConnectionString != "") // if there is something in the config file work with it
{
dataConnection = new SqlConnection(ConnectionString);
}
else
{
dataConnection = new SqlConnection();
}
Upvotes: 1