Click here to Skip to main content
15,880,543 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I created a quick windows Form and class:
C#
namespace TestClassScope
public partial class Form1 : Form
{
  public Form1()
   {
     InitializeComponent();
     Class1 myClass = new Class1();
   }
  private void button1_Click(object sender, EventArgs e)
  {
     string stuffy = myClass.MyStuff;
  }
}

created a simple class:

namespace TestClassScope
{
    class Class1
    {
        private string myStuff = "Stuff";
        public string MyStuff 
        {
            get { return myStuff; }
            set { myStuff = value; }
        }
    }

The compiler error i get is a sguiggly line under myClass and a tag that states:

"The name 'myClass' does not exist in the current context". When I instantiate the class within the button1_click it's ok. It would be nice to have a class I can instantiate in the public Form1() method and then available throughout all my other form methods. Is this not possible?

I'm a lille jr. to Windows forms. Any ideas on how to deal with this scoping problem?
Posted
Comments
[no name] 30-Aug-14 17:14pm    
Yes it's possible. You are instantiating your Class1 in the form constructor and when that is done, you don't have a myClass anymore. Study up on variable scoping. You want to move your declaration to the class level.

1 solution

You should be aware of scope rules, the myClass in your form's constructor is scoped to that method and is not available outside that constructor, you should put the variable in the form as a property so all the methods have access to it.

Do the following :

C#
public Form1()
 {
   InitializeComponent();   
 }

Class1 myClass = new Class1(); // a variable for the entire form
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900