Search code examples
c#arraysstringvariable-declarationvariable-initialization

Initialization of C# string array


I want to declare a string array, I was using this way of doing it:

string[] matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);

which worked perfectly.

Now I want to enclose the Directory.GetFiles call in a try/catch block, but I can't also have the declaration of the string array in there because then it won't be in the right scope to use it outside of the try block. But if I try this:

string[] matchingActiveLogFiles;
    try
    {
        matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);
    }
    catch (Exception ex)
    {
        //log error
    }
            

I have not initialized the string array so I have an error. So I am wondering what is best practise in this situation, should I declare the string array outside the try block? And if so how?


Solution

  • This will initialize your array:

    string[] matchingActiveLogFiles = {};
        try
        {
            matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);
        }
        catch (Exception ex)
        {
            //log error
        }
    

    But I'm wondering, what error are you getting?

    Even with an uninitialized array, the above code should work.

    I also noticed that you have "matchingActiveLogFiles" on line 1 and "matchingFiles" on line 4. Perhaps that's your problem?