Recursion in the constructor

Please review the following code snippet. I get a nullreferenceexception in "this.directories.Add (new directory (s))". Recursion seems to work as long as it doesn't β€œunwind”, at which point β€œnew directory (s)” seems to be null. I'm not sure why it behaves this way, I thought there might be special rules, because recursion is in the constructor. Please, help.

namespace AnalyzeDir { class directory { public string[] files; public ArrayList directories; public string mypath; public string myname; public directory(string mp) { mypath = mp; myname = mypath.Substring(mypath.LastIndexOf("\\")); files = Directory.GetFiles(mypath); fillDirectoriesRescursive(); } public void fillDirectoriesRescursive() { string[] dirpaths = Directory.GetDirectories(mypath); if (dirpaths != null && (dirpaths.Length > 0)) { foreach(string s in dirpaths) { this.directories.Add(new directory(s)); } } } 
+4
source share
2 answers

You did not initialize directories to be anything.

I would suggest not to do this in the constructor, but instead move it to a method call. It goes back to "implied behavior" where you should not have complex external system logic inside accessory properties.

You are also using the very old ArrayList construct. Instead, I suggest using ICollection<directory> . More type safety and all that.

+7
source

You did not initialize directories at all.

+1
source

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


All Articles