Reputation: 245
I am programming in C# and I keep getting an error for my string variable result
.
When I hover over the line return result
it says use of unassigned local variable.
Do I have to assign result a value before I use it? How come i do not get the same error for SqlDataReader
reader?
string searchbyLastName(string lastname)
{
string result;
SqlDataReader reader;
try
{
reader = myCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (reader["LastName"].ToString() == lastname)
{
result = reader.GetString(0);
break;
}
}
return result;
}
else
return "No results found";
}
catch (Exception)
{
return("Database Error");
}
}
Upvotes: 1
Views: 873
Reputation: 39329
The compiler needs to know you have definitely assigned a value to a variable, at the point where you are using that value.
In your case reader
is always assigned a value (reader = myCommand.ExecuteReader();
), but result
isn't, because that depends on reader["LastName"].ToString() == lastname
being true, which may never happen (even if you designed the system so that in reality you always find a match - the compiler doen't know that).
So somewhere before you enter that while-loop you have to assign a value. result = null
would be enough. This value could also be used to signal a "lastname not found" condition to the calling code.
Upvotes: 0
Reputation: 124760
if (reader["LastName"].ToString() == lastname)
If that is never true then result
is not initialized. The SqlDataReader
is always initialized prior to being used. Just initialize the string.
var result = "";
Upvotes: 3