Beginner question on classes

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;
}
 
S

Shiva

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;
}
 
F

Frank Eller

Btw: if you declare "c" in Main _after_ Application.Run(), the class would
be instantiated _after_ the application was closed anyway ...

Regards,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top