views:

402

answers:

3

I have a string property that defines a filename for an xml file. When the user inputs this filename into the property, I have the setter calling a parseXml() function immediatly after setting 'fileName = value' to populate a dataTable with the data from the XML file so it displays in the designer. For some reason, when I have this function call in the property setter, the setter ends up getting called every twice every time I change the property, with the 2nd time being an empty string which causes an error. Why is it doing this?

public String FileName
{
    get { return fileName; }
    set 
    {
        fileName = value;
        parseXmlFile();
    }
}
+8  A: 

My initial guess would be that something in parseXml() is calling that setter again. What happens if you remove the call to parseXml()? Have you tried debugging and stepping through the code as it is running to see what exactly is calling the setter the second time?

If you slap a breakpoint on filename = value; and hit it, what does the callstack window show you?

Nathan Taylor
The first time the property is called, the fileName and 'value' values are the correct input from the user. The parseXml function is executed with no problems. Immediatly after, it goes through the setter again and now 'value' is the empty string so it resets the fileName to the emptyString and executes parseXml() with an empty fileName and then it causes an error.
alexD
And what does the callstack look like on that second write? From where was the setter called?
Lasse V. Karlsen
And what does the **callstack window** show the second time?
Nathan Taylor
Put a breakpoint on the set {...}. When it stops there, check teh call stack. You need to figure out who is making teh second request.
Partha Choudhury
+3  A: 

Short answer: it shouldn't. More helpful: maybe you cause the second call yourself? Set the debugger on the setter and the second time it is called, inspect the call stack.

Teun D
Thank you, that answers my question. I just wanted to make sure it was a problem in my code and not a conflict in .NET before I wasted too much time debugging when I should be refactoring.
alexD
A: 

As a complete aside to the problem you're having, putting expensive IO operations behind property setters is a little off kilter.

If you want to open up a file and parse stuff etc it would be better to have a separate method named appropriately that does the IO and sets this property (filename) at the end when the method successfully completed its work.

Jason Punyon
Not really an answer to his problem - I said the same thing as a comment on his question.
Philip Wallace