1

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"); } } 

2 Answers 2

3
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 = ""; 
Sign up to request clarification or add additional context in comments.

7 Comments

Bad practice. Use var result = String.Empty;
@DanHunex: No thank you, please explain why you consider it a "bad practice". There hasn't been any actual semantic difference in quite some time due to string interning. Do you simply enjoy typing?
Why do you think String.IsNullOrWhitespace is added? Because people sometimes write " " instead of "" . But String.Empty always guarantee that it is empty
@DanHunex: They do? Weird. I have never, in over a decade of work, seen that error. I think I'll stick with "", thanks though. PS: IsNullOrWhitespace was almost certainly not added to account for typos when attempting to initialize a variable to an empty string. It's meant to check for empty input, not incorrectly initialized variables.
Well, you can also see this but i m not trying to convince you with more than 10 years of experience stackoverflow.com/questions/2905378/string-empty-versus
|
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.