new to C#  - exit while

VBdotnet2005
VBdotnet2005 used Ask the Experts™
on
I am new to C#. This is a sample. How can I exit while if 'q' ? Break below in C#, it exit "if" only. If 'q' I need to exit from while loop .

                  ...

                  while (true)
                            {
                               
                                if (line_tmp == "q")
                                {
                                    break;
                                }
                             
                                else
                                {
                                    Console.WriteLine("There is test");
                                }
                            }
                  ...
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Rikin ShahMicrosoft Dynamics CRM Consultant

Commented:
Replace break; with return;
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009

Commented:
...or initialize the variable and change the conditional check:

    line_tmp = "";
    while (line_tmp != "q")
    {

    }
kaufmedGlanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
it exit "if" only
break has no effect on if blocks--it is only applicable for loops and switch statements. Why do you think it is exiting the if only?
Systems Development / Support Specialist
Commented:
Try executing this , it works perfectly fine.
   class Program
    {
        static void Main(string[] args)
        {
            string line_tmp = "q";
            while (true)
            {
                if (line_tmp == "q")
                {
                    break;
                }
                else
                {
                    Console.WriteLine("There is test");
                }
                Console.WriteLine("done is test");
            }
            Console.Read();
        }
    }

Open in new window

kaufmedGlanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
I wonder if I might be humored in getting an answer to:  what is different about the code posted in the selected "solution" and the original post? I wish all my answers were that easy.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial