Click here to Skip to main content
14,297,338 members
Rate this:
Please Sign up or sign in to vote.
See more:
Below is the code where I want to concatenate a string variable with string:
public void formQueryString()
        {
            string filterQuery;
            int chk=0;
            if (rbHomeDelivery.Checked)
            {
                filterQuery = "Home_Delivery like yes";
                chk=1;
            }
            if(rbTakeaway.Checked)
            {
                filterQuery = "Take_Away like yes";
                chk=1;
            }
            if (cbOpenAllDay.Checked && chk==1)
            {
                filterQuery = filterQuery + " or Open_All_Day like yes"; //Line with error
            }
            else
            {
                filterQuery = filterQuery + "Open_All_Day like yes";
            }
        }


It is giving error that "use of unassigned local variable filterQuery ".

Now I don't know why it is giving error.

Please let me know the error

Thanks in advance.
Posted
Updated 11-Jun-16 7:40am
Comments
Amir Mahfoozi 6-Apr-13 7:44am
   
change "string filterQuery;" to "string filterQuery = string.Empty;"
Philippe Mori 12-Jun-16 18:52pm
   
Read the error message. It tell exactly what is the problem.

Then it is trivial to see that if the first two conditions are false and the third one is true then filterQuery would be used before having been initialized.

In fact, the compiler even tell you on which line the uninitialized variable is used!
Rate this:
Please Sign up or sign in to vote.

Solution 1

try to initialize filterQuery
like string filterQuery="" or string filterQuery=string.Empty;
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

simply add
string filterQuery="";
at the place of
string filterQuery;
   
Comments
Rhushikesh 6-Apr-13 7:52am
   
thank u pallaviji
Rate this:
Please Sign up or sign in to vote.

Solution 3

Hi,

Although everyone gives the correct answer. i would like to add more.

Error it self says what is the problem. The line where you are having issue is using filterQuery variable. Either you can assign default value of the string at the time of declaration or you need to add some conditions at the time of concatenation. but the best option is to assign default value or you can say blank in case of string.

Whenever you are creating some variable don't forget to assign some value to prevent such kind of errors. Sometimes you may not able to test all the possible scenarios. so best way to solve such error is,
//examples
String str = default(String);
Customer cust = default(Customer);


Hope this will help you.

Best luck
-Amit
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100