none
C# Variable scope - problem RRS feed

  • Question

  • 

    Hi there,

    Why would the fn variable not be available in this case ?

     

    When I put public in from of string everything falls appart.

     

     

     

    Wednesday, November 29, 2017 1:29 PM

All replies

  • To put code into your post, please use the "Insert code block" icon .

    That way people (like me) can copy/paste your code to try it out!

    But to your question: You haven't actually said what the exact error message is, Are you sure that VS is actually complaining about the variable not being available?

    Because one issue I can see is that the fn variable is potentially not going to be initialised. This would happen if your Documents collection is empty. 

    So Visual Studio may actually be complaining about a variable that may not be initialised.

    To resolve that, simply initialise it with a default value.

    string fn = "";

    • Proposed as answer by Stanly Fan Thursday, November 30, 2017 1:49 AM
    Wednesday, November 29, 2017 1:34 PM
  • If you want to send all of the documents, then put the definition of the variable and the SendMesage line inside the foreach. Maybe some other modifications are needed, because now fn only holds the last filename.

    • Edited by Viorel_MVP Wednesday, November 29, 2017 1:46 PM
    • Proposed as answer by Stanly Fan Thursday, November 30, 2017 1:49 AM
    Wednesday, November 29, 2017 1:44 PM
  • Ah yes, I admit I was only thinking of the syntax rather than what the code is apparently trying to do!

    So as Viorel says you may also want to move both the fn variable and the SendMessage line to inside the foreach loop.

    Wednesday, November 29, 2017 2:13 PM
  • In the first case you are probably getting a use of an unassigned local variable syntax error.

    The only use case it would actually be assigned is 1) when documents is a populated 'list/collection' and then when Path.GetFileName gets to assign the value.

    Hover your mouse over the word with the squigly line and the IDE will tell you the problem, or look in the Error List dockable dialog. 

    In the second case, well it could be anything, but I'm thinking you deleted a closing bracket or didn't end a line with a semi-colon. But really, without more information it's hard to say for certain.
    Wednesday, November 29, 2017 9:58 PM