How to get around this unassigned variable problem?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,

I have a piece code like this:

static void Main()
{
Utility db;
try
{//create db connection, fill dataset...
db = new Utility();

}
catch(Exception e)
{
MessageBox.Show("Exit...");
}

if( db != null) <--- .net does not like it.
{
Application.Run(new DataForm(db));
}

}
When compiling, .NET complains that db at "if( db != null)" is undefined.
But that what I want to test. How could I get around of this problem?

Thanks,

Karl
 
Karl said:
I have a piece code like this:

static void Main()
{
Utility db;
try
{//create db connection, fill dataset...
db = new Utility();

}
catch(Exception e)
{
MessageBox.Show("Exit...");
}

if( db != null) <--- .net does not like it.
{
Application.Run(new DataForm(db));
}

}
When compiling, .NET complains that db at "if( db != null)" is undefined.
But that what I want to test. How could I get around of this problem?

Set db to null to start with:

Utility db = null;
 
The problem is that you don't exit in the catch block, you only show a
message, and then continue on. Add a return after the exit block to ensure
that the unitialized variable won't be accessed.

Alternatively, you can do Utility db = null; -- However, that's not really
your intention, and the compiler can't find mistakes in your code (like this
one -- you'd use the null value later on and get a NullReferenceException).
-Michael
MVP
 
I read right over the db != null part :S. So it wouldn't throw an exception
later on. My mistake.

Either way still works in this sample though. :)
 
Back
Top