Passing new class instance to method

G

Guest

Hi I am trying to access my XmlTextWriter class within a called method, but
am unable to do this. I have initiated the new class within the main method

static void Main
{
XmlTextWriter tw = new XmlTextWriter(fileName,null);
//lots more code including xml text writing calls
// i then call my method
MyMethod(text);
}

public static void MyMethod(string text)
{
tw.WriteStartElement("stuff goes here ect"); //this does not work
//more xml write stuff
}

How do i use my tw object everywhere?
Thanks for your help
 
M

Michael Voss

Matt said:
Hi I am trying to access my XmlTextWriter class within a called method, but
am unable to do this. I have initiated the new class within the main method

static void Main
{
XmlTextWriter tw = new XmlTextWriter(fileName,null);
//lots more code including xml text writing calls
// i then call my method
MyMethod(text);
}

So you declared tw inside a static method; whenever you leave that method,
tw is out of scope.
public static void MyMethod(string text)
{
tw.WriteStartElement("stuff goes here ect"); //this does not work

Certainly, since tw is not visible from here.
//more xml write stuff
}

How do i use my tw object everywhere?

Declare tw as a static variable of your class (outside any method):
<code>

class YourClass
{
private static XmlTextWriter tw;

// and use it in your Main() method:

static void Main()
{
// some stuff
tw = new XmlTextWriter(fileName,null);
//...
</code>

So tw will be visible in every method of YourClass.
 

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