How to do constructor chaining in C#

前端 未结 8 1546
挽巷
挽巷 2020-11-22 16:25

I know that this is supposedly a super simple question, but I\'ve been struggling with the concept for some time now.

My question is, how do you chain constructors

相关标签:
8条回答
  • 2020-11-22 16:58

    I hope following example shed some light on constructor chaining.
    my use case here for example, you are expecting user to pass a directory to your constructor, user doesn't know what directory to pass and decides to let you assign default directory. you step up and assign a default directory that you think will work.

    BTW, I used LINQPad for this example in case you are wondering what *.Dump() is.
    cheers

    void Main()
    {
    
        CtorChaining ctorNoparam = new CtorChaining();
        ctorNoparam.Dump();
        //Result --> BaseDir C:\Program Files (x86)\Default\ 
    
        CtorChaining ctorOneparam = new CtorChaining("c:\\customDir");
        ctorOneparam.Dump();    
        //Result --> BaseDir c:\customDir 
    }
    
    public class CtorChaining
    {
        public string BaseDir;
        public static string DefaultDir = @"C:\Program Files (x86)\Default\";
    
    
        public CtorChaining(): this(null) {}
    
        public CtorChaining(string baseDir): this(baseDir, DefaultDir){}
    
        public CtorChaining(string baseDir, string defaultDir)
        {
            //if baseDir == null, this.BaseDir = @"C:\Program Files (x86)\Default\"
            this.BaseDir = baseDir ?? defaultDir;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:02

    There's another important point in constructor chaining: order. Why? Let's say that you have an object being constructed at runtime by a framework that expects it's default constructor. If you want to be able to pass in values while still having the ability to pass in constructor argments when you want, this is extremely useful.

    I could for instance have a backing variable that gets set to a default value by my default constructor but has the ability to be overwritten.

    public class MyClass
    {
      private IDependency _myDependency;
      MyClass(){ _myDependency = new DefaultDependency(); }
      MYClass(IMyDependency dependency) : this() {
        _myDependency = dependency; //now our dependency object replaces the defaultDependency
      }
    }
    
    0 讨论(0)
提交回复
热议问题