Class scope

G

Guest

Hello, I have a newbie question about class scope. I am writting a little
program that will move files to one of two empty folders. I am having a hard
time understanding scope. So this will be a two part question.

Part 1:

I have a form with a text box on it that I want to spit out results to.
Sample code:


namespace MyApplication
{
public class MyApplication : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox txtMessage;
private System.ComponentModel.Container components = null;

public FileProcess()
{
//Some Code to process my file
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
//etc.....
}

static void Main()
{
Application.Run(new FileProcess());
}

public static void OnChanged(object source, FileSystemEventArgs e)
{
txtMessage.Text = "File created."
//***** THIS IS WHERE I GET MY ERROR!
}
}

So as you can see, in the "OnChange" function, I cannot see the txtMessage
object. I do not get intellecence(sp?) and cannot see the object, like it's
out of scope. How can I make it so I can see the text box from anywhere in
my code? Like what if I was inside the code of a new class that I had
created and wanted to spit out some results to my form?


Part 2:

My second question is related. I built a class that reads some values from
an XML file. Those values are set to some properties. In my main code you
see above I have instanciated(sp?) an instance of this class and can see all
my properties fine. But then when I go into another class I cannot see that
intance and properties anymore. I know I can just intanciate another intance
of the XML class to get the values again, but I don't want to have to keep
running that code to read the XML every time I need the values. Is there a
way to intanciate the class globally? So no matter where I am I can see the
properties?

Thanks for you help.
Michael.
 
G

Guest

You should be able to see the txtMessage control from inside OnChanged, but I
notice that you're missing a closing brace ("}"). Depending on where you put
it, it can change the meaning of what you've typed.

For your second question, you could look into the Singleton pattern which
allows you to have a single instance of a class everywhere. To implement it,
you create a static method on your class that returns a static private
variable that has an instance of your object.
 
M

Michael Taylor

If you want to reference non-static members of a class in a method the
method must also be non-static. Try removing the "static" modifier from
OnChanged.
 

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