Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
I created a quick windows Form and class:
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 30-Aug-14 12:09pm
Comments
Wes Aday at 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

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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 :
 
public Form1()
 {
   InitializeComponent();   
 }
 
Class1 myClass = new Class1(); // a variable for the entire form
  Permalink  

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



Advertise | Privacy | Mobile
Web01 | 2.8.150326.1 | Last Updated 31 Aug 2014
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100