Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Recursion in Constructor

Please look at the following code snippet. I'm getting a nullreferenceexception at "this.directories.Add(new directory(s));". The recursion seems to be working until it "unwinds", at which point "new directory(s)" seems to be a null. I'm not sure why it is behaving this way, I thought perhaps there are special rules because the 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);
        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));
like image 752
dmil Avatar asked Feb 22 '23 02:02


1 Answers

You haven't initialized directories to be anything.

I'd suggest not doing this in the constructor, but instead moving it to a method call. It goes back to "implied behavior", where you shouldn't have big complicated foreign system logic inside of property accessors.

You are also using a very old construct, ArrayList. I'd suggest using an ICollection<directory> instead. More type-safety and all that.

like image 55
Bryan Boettcher Avatar answered Mar 03 '23 03:03

Bryan Boettcher