This is probably a very simple Object Oriented Programming question. What I am trying to do is take 2 empty objects, use a query to pull data from a database, populate the empty objects with the data returned from the query, and then assert against them. See the code below:
object test1;
object test2;
using (SqlConnection dbconnection = new SqlConnection(expconnstr))
{
dbconnection.Open();
var expcommand = new SqlCommand(expectedquery, dbconnection);
var actcommand = new SqlCommand(actualquery, dbconnection);
using (SqlDataReader expreader = expcommand.ExecuteReader())
{
if (expreader.Read())
{
test1 = expreader.GetValue(0);
expreader.Close();
}
}
using (SqlDataReader actreader = actcommand.ExecuteReader())
{
if (actreader.Read())
{
test2 = actreader.GetValue(0);
actreader.Close();
}
}
}
Assert.AreSame(test1, test2);
I wrote a very similar test method in VB following the same patterns and the VB code executed just fine. However whilst transitioning from VB to C#, I run into issues such as these. The compiler says “Use of unassigned variable” at the assert. However, I thought I was assigning to a value within the code block above. What am I doing wrong?
The possibility exists that
actreader.Read()returns false, thustest2may never get assigned and the compiler error.You can remedy the issue by explicitly setting
test1&test2initially tonull: