How to solve unassigned 'out' parameter error?

c#

Solution

You want a `ref` parameter not an `out` parameter since you're both accepting the value and setting a new value.

int iCount = 0;
getFileCount(_dirPath, ref iCount);

private void getFileCount(string _path, ref int iCount )
{          
    try
    {
        // gives error :Use of unassigned out parameter 'iCount' RED Underline
        iCount += Directory.GetFiles(_path).Length;

        foreach (string _dirPath in Directory.GetDirectories(_path))
            getFileCount(_dirPath, ref iCount);
    }
    catch { }
}

even better, don't use out parameters at all.

private int getFileCount(string _path) {
    int count = Directory.GetFiles(_path).Length;
    foreach (string subdir in Directory.GetDirectories(_path))
        count += getFileCount(subdir);

    return count;
}       

and even better than that, don't create a function to do something the framework already does built in..

int count = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Length

and we're not done getting better... don't waste space and cycles creating an array of files when all you need is a length. Enumerate them instead.

int count = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).Count();

Problem

I am trying count total number of files in all the sub folder of a given path. I am using recursive function call. What could be the reason? Code: ``` int iCount =0; getFileCount(_dirPath, out iCount); private void getFileCount(string _path, out int iCount ) { try { // gives error :Use of unassigned out parameter 'iCount' RED Underline iCount += Directory.GetFiles(_path).Length; foreach (string _dirPath in Directory.GetDirectories(_path)) getFileCount(_dirPath, out iCount); } catch { } } ```

Original source

Related problems