Link to home
Start Free TrialLog in
Avatar of CipherIS
CipherISFlag for United States of America

asked on

C# - How to determine if a variable has value or needs to be initialzed.

I converted a 2008 app to 2012.  Below is a snippet of code i'm working with.  I want to know in the Process method if I need to initialize my masterDoc variable.  If it was used already I want to use what is in the local variable if not then I want to initialize.

Any ideas?

public class PrintApp
{
    protected Microsoft.Office.Interop.Word.Application wApp;
    protected Microsoft.Office.Interop.Word.Document masterDoc;

    private void Initialize()
    {
            masterDoc = new Microsoft.Office.Interop.Word.Document();  
            masterDoc.Application.Visible = false;
    }

    private void Process()
    {
        //Want to use value that was initialized previously.
        masterDoc = new Microsoft.Office.Interop.Word.Document();  
        masterDoc.Select();
        masterDoc.SaveAs
    }
}

Open in new window

Avatar of Jens Fiederer
Jens Fiederer
Flag of United States of America image

if (masterDoc == null) {
      masterDoc = new Microsoft.Office.Interop.Word.Document();  
}
Avatar of CipherIS

ASKER

That not working.  When the code gets to

masterDoc.Activate();

it errors.
I don't see any "Activate" in your code.

If it is a NullReferenceError you may need to do the initialization before Activate is called.
Avatar of Kalpesh Chhatrala
you can use like below.

        // Open a doc file.
	Microsoft.Office.Interop.Word.Application wApp = new Microsoft.Office.Interop.Word.Application();
	Microsoft.Office.Interop.Word.Document masterDoc = wApp.Documents.Open("C:\\word.doc");

	// Loop through all words in the document.
	int count = masterDoc.Words.Count;
	for (int i = 1; i <= count; i++)
	{
	    // Write the word.
	    string text = masterDoc.Words[i].Text;
	    Console.WriteLine("Word {0} = {1}", i, text);
	}
	// Close word.
	wApp.Quit();

Open in new window

I cannot test where I am now, but if my memory is good, you cannot Activate a document when the application is not Visible. This makes sense. What is the use of activating something that is not visible.

Note that you do not need to activate the document to work with it with code. A lot of the stuff you see when recording a macro assume that the user is working with the document, and is thus useless when manipulating the document through code.
ASKER CERTIFIED SOLUTION
Avatar of CipherIS
CipherIS
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Saved the document in the initialize method.