How to resolve an unrecognized "out" error?

I am trying to calculate the total number of files in the entire subfolder of this path. I am using a 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 { } } 
+6
source share
2 answers

You need a ref parameter, not an out parameter, since you both take a value and set 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 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 already built-in framework.

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

and we are not improving ... do not lose space and loops by creating an array of files when you only need length. List them instead.

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

Parameters that are passed as input must be initialized inside the function. Since iCount is not yet initialized, the value is unknown, and not where to start, even if it is an integer whose default value is 0.

I would recommend not binding the out parameter along with the recursive function. Instead, one could use a regular return parameter. Microsoft itself proposes through some rules of static analysis to avoid possible parameters .

0
source

Source: https://habr.com/ru/post/972243/


All Articles