Beginner question on classes

  • Thread starter Thread starter Dave
  • Start date Start date
D

Dave

Why does the following code generate the error:
//The type or namespace name 'c' could not be found (are you missing a using
directive or an assembly reference?)


static void Main()
{
Application.Run(new Form1());
class1 c = new class1();
}

private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show(c.x.ToString());
}

class class1
{
public int x;
}
 
c defined in Main() is local to that method only. It cannot be accessed from
anywhere (in this case button1_click). Declaring c at the class level will
give the output you are looking for.

Why does the following code generate the error:
//The type or namespace name 'c' could not be found (are you missing a using
directive or an assembly reference?)


static void Main()
{
Application.Run(new Form1());
class1 c = new class1();
}

private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show(c.x.ToString());
}

class class1
{
public int x;
}
 
Btw: if you declare "c" in Main _after_ Application.Run(), the class would
be instantiated _after_ the application was closed anyway ...

Regards,
 
Back
Top