Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Below is the code where I want to concatenate a string variable with string:
C#
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!

try to initialize filterQuery
like string filterQuery="" or string filterQuery=string.Empty;
 
Share this answer
 
simply add
string filterQuery="";
at the place of
string filterQuery;
 
Share this answer
 
Comments
Rhushikesh 6-Apr-13 7:52am    
thank u pallaviji
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,
C#
//examples
String str = default(String);
Customer cust = default(Customer);


Hope this will help you.

Best luck
-Amit
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900