We help IT Professionals succeed at work.

foreach C# syntax problem

codefinger
codefinger asked
on
556 Views
Last Modified: 2012-02-09
private void button1_Click(object sender, EventArgs e)
        {
            string str_msg;
            str_msg = "Hello World!";
            int intger,x;
            List<int> lstints;
            lstints = new List<int>();
            intger = 1;
            
            for(x = 0;x <=5;x+=1){
                lstints.Add(intger);
                str_msg = "The current value of x is " + x.ToString();
                MessageBox.Show(str_msg);
            }

            foreach(int x_intger in lstints){

                MessageBox.Show(x_intger.ToString());
            
            }

Open in new window



Experienced with VB.NET, but all the jobs are asking for C#, so trying to learn it now using VS 2010 Express.  The above does not do quite what I expected  -- the second loop just shows a "1" five times, should have been 1,2,3, etc....

What did I do wrong?
Comment
Watch Question

IT Business Systems Analyst / Software Developer
CERTIFIED EXPERT
Top Expert 2015
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
AshokSr. Software Engineer
CERTIFIED EXPERT

Commented:
Just as mccarl said.

      for (x = 0; x <= 5; x += 1) {
        lstints.Add(x);   // Change this line
        str_msg = "The current value of x is " + x.ToString();
        MessageBox.Show(str_msg);
      }

HTH
Ashok

Author

Commented:
DOH!  So obvious now....clearly I have a long way to go....
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.