Error

  • Thread starter Thread starter A.M
  • Start date Start date
A

A.M

Hi,

Why C# compiler returns "Use of unassigned local variable 'reportParams'"
during compilation of this code?



System.Data.SqlClient.SqlDataReader reportParams;
try
{
reportParams = SqlHelper.ExecuteReader(Global.ConnectionString ,
"up_Report");
}
catch (Exception ex)
{
Log(ex);
Response.Redirect ("ErrorReport.aspx",true);
}
finally
{
reportParams.Close();
}




Thanks,
Ali
 
If ExecuteReader throws an exception, the variable reportParams will not be
assigned a value. So the line "reportParams.Close()" will be using a
variable that has not been assigned to.

Easiest way around this is to assign reportParams null at the start of the
function and check for null before closing it

--
Jared Parsons [MSFT]
(e-mail address removed)
This posting is provided "AS IS" with no warranties, and confers no rights.
OR if you wish to include a script sample in your post please add "Use of
included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm"
 
Hello Ali,

Well, the function SqlHelper.ExecuteReader could throw an exception and in
that case reportParams doesn't get initialized. Than, the finally section
gets executed and you call reportParams.Close but reportParams is not
initizalized.
Hi,

Why C# compiler returns "Use of unassigned local variable 'reportParams'"
during compilation of this code?



System.Data.SqlClient.SqlDataReader reportParams;
try
{
reportParams = SqlHelper.ExecuteReader(Global.ConnectionString ,
"up_Report");
}
catch (Exception ex)
{
Log(ex);
Response.Redirect ("ErrorReport.aspx",true);
}
finally
{
reportParams.Close();
}




Thanks,
Ali

Adrian Vinca [MSFT], Developer Division
--------------------------------------------------------------------
This reply is provided "AS IS", without warranty (express or implied).

Note: For the benefit of the community-at-large, all responses to this
message are best directed to the newsgroup/thread from which they
originated.
 
Back
Top