views:

679

answers:

3

How can i do this? (c#) Basically, i want to be able to sort of, comment out a bracket. but not really. I guess I want to close brackets out of order. That's probably not possible. I can obviously implement this in full separate if clauses, but this would considerably lighten my code.

P.S.: I am trying to place the "//do something" code, either in a foreach loop, or for a single instance with an unrelated (to that of the foreach loop) argument, depending on a condition. I hope this helps clear it up.

pseudocode (what i'm trying to do, if you could close brackets out of order):

im aware this is no where near valid code, it is pseudocode as i stated.

i havent looked at the second post yet, but the first post (Sean Bright), thank you, but the condition is unrelated to the number of entries (there will always be files in the directory, regardless of if i want the loop to execute)

extracting the //dosomething code into a function will work. I'm not sure how i overlooked that. I suppose I was wondering if there was a simpler way, but you are correct. thank you.

if (isTrue)
{
    //START LOOP
    string [] fileEntries = Directory.GetFiles(LogsDirectory, SystemLogFormat);
    foreach(string fileName in fileEntries)
    {
       using (StreamReader r = new StreamReader(fileName))
       {
    /* The previous two blocks are not closed */
}
else
{
    using (StreamReader r = new StreamReader(SingleFileName))
    {
    /* The previous block is not closed */
}

// do all sorts of things

if (isTrue)
{
    /* Close the two unclosed blocks above */
        }
    }
}
else
{
    /* Close the unclosed block above */
    }
}

thanks!

(indents are weird, sorry, its the forums doing)

+6  A: 

Why not just do this:

string [] fileEntries = null;

if (isTrue) {
    fileEntries = Directory.GetFiles(LogsDirectory, SystemLogFormat);
} else {
    fileEntries = new string [] { SingleFileName };
}

foreach(string fileName in fileEntries) {
    using (StreamReader r = new StreamReader(fileName)) {
        /* Do whatever */
    }
}
Sean Bright
+1 That's the approach I took to a similar problem just yesterday
AdamRalph
+5  A: 

Refactor the file processing part into a separate function:

public void OriginalFunction() {
    if ( isTrue ) {
        string [] fileEntries = Directory.GetFiles(LogsDirectory, SystemLogFormat);
        foreach(string fileName in fileEntries) {
            ProcessFile(fileName);
        }
    } else {
        ProcessFile(SingleFileName);
    }

}

public void ProcessFile( string name ) {
    using (StreamReader r = new StreamReader(name))
    {
       // Do a bunch of stuff
    }
}
Eric Petroelje
A: 

Use your conditional to determine how you're going to create your StreamReader, then pass that in the using() like normal.

Chris Missal