Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Invalid token 'while' in class, struct, or interface member declaration (while loop not working) [duplicate]

I'm new to c# but quite familiar with c, this error however doesn't make much sense to me, as I have specifically followed the required syntax shown on http://msdn.microsoft.com/en-us/library/2aeyhxcd.aspx

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    int years = 1;
    while (years <=10) {

    public Form1()
    {
        InitializeComponent();
    }

    private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        int value = Convert.ToInt32(bushels1.Text);
        numericUpDown1.Maximum = value;
    }

    private void bushels1_Click(object sender, EventArgs e)
    {

    }

    private void nextYear_Click(object sender, EventArgs e)
    {

    }
    }
   }
}
like image 619
Szymon Zmudzki Avatar asked Aug 16 '26 03:08

Szymon Zmudzki


2 Answers

You have while directly inside the class, it should be part of a method, You can't write statements like while directly inside the class.

public partial class Form1 : Form
{
    int years = 1;
    while (years <=10) {
   //^^

It should be part of method like:

public partial class Form1 : Form
{
    int years = 1;
    public void SomeMethod()
    {
       while (years <=10) {
      //rest of your code
    }
like image 125
Habib Avatar answered Aug 18 '26 18:08

Habib


your while loop must be in a method, you have it in the variable/method declaration area. Remove it and place inside a method.

like image 31
T McKeown Avatar answered Aug 18 '26 17:08

T McKeown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!