0

I am adding in a few search parameters to my MySQL search functions; I basically copied the existing commands (with some obvious changes), but I got an unexpected error:

Use of unassigned variable x

This is what I originally had in my code:

string searchOldVar;
string searchNewVar;

if (!String.IsNullorWhitespace(oldVar))
    searchOldVar = " AND col_OldVar LIKE %" + oldVar = "%";
else searchOldVar = String.Empty;

if (!String.IsNullorWhitespace(newVar))
    searchNewVar = " AND col_NewVar LIKE %" + newVar = "%";

// MySQL Search command
    + searchOldVar
    + searchNewVar // Unassigned variable error
    + ";";

So then I added the line:

if (!String.IsNullorWhitespace(newVar))
    searchNewVar = " AND col_NewVar LIKE %" + newVar = "%";    
else searchNewVar = String.Empty;

and the error disappeared.

Why?

Ben
  • 2,433
  • 5
  • 39
  • 69
  • 1
    The local variable has *not* been definitely assigned: thus it is considered *unassigned*. In the erroring case, `searchNewVar` is only assigned "sometimes" based on some (unknown at compile time) condition. Anyway, consider *searching for error messages* before asking a question :} – user2864740 May 31 '16 at 04:39
  • Compiler thinks that it may not enter in if condition so thinks that it may not be assigned to any value. – Mairaj Ahmad May 31 '16 at 04:40
  • A quick googling may solve this : https://www.google.co.in/search?q=Use+of+unassigned+variable+x&oq=Use+of+unassigned+variable+x&aqs=chrome..69i57&sourceid=chrome&ie=UTF-8 – sujith karivelil May 31 '16 at 04:42
  • 1
    @user2864740 I see. So it would only be assigned if it had a value - and adding the `String.Empty` gives it a value either way. – Ben May 31 '16 at 04:44
  • @Ben Yes, that's correct. Another alternative (which I don't like) is to assign the variable a "default value" sooner, perhaps at declaration. In this particular case I may consider using the `?:` (conditional operator) expression or a separate method. Also, *use SQL "SqlParameter" placeholders* for more robust code :) – user2864740 May 31 '16 at 04:45

0 Answers0