After reading this Constructor chaining question I am just curious to know why would any one do constructor chaining?
Could some one please shed some light on type of scenarios where this might be useful.
Is this a good programming practice?
It's absolutely a good practice for two main reasons:
To avoid code duplication
class Foo
{
public Foo(String myString, Int32 myInt){
//Some Initialization stuff here
}
//Default value for myInt
public Foo(String myString) : this(myString, 42){}
//Default value for both
public Foo() : this("The Answer", 42){}
}
To enforce good encapsulation
public abstract class Foo
{
protected Foo(String someString)
{
//Important Stuff Here
}
}
public class Bar : Foo
{
public Bar(String someString, Int32 myInt): base(someString)
{
//Let's the base class do it's thing
// while extending behavior
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With