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
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;
}
}
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
}
}