CipherIS
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?
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
}
}
ASKER
That not working. When the code gets to
masterDoc.Activate();
it errors.
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.
If it is a NullReferenceError you may need to do the initialization before Activate is called.
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();
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Saved the document in the initialize method.
masterDoc = new Microsoft.Office.Interop.W
}