This is easy to work around, but I just curious if I could be using a language feature or possibly the fact that the language disallows it means I'm making a logical error in class design.
I'm doing a self review of my code to help "harden" it for re-use and I just came accross:
public partial class TrackTyped : Component { IContainer components = null; public TrackTyped() : base() { InitializeComponent(); } public TrackTyped(IContainer container) : base() { container.Add(this); InitializeComponent(); } }
What I usually do when I see the same line of code in two constructors is make one call the other with "this()" but I can't seem to do it.
If I read the spec right (I just started trying to read the spec so I may not be right):
10.11 Instance Constructors constructor-declarator: identifier ( formal-parameter-listopt ) constructor-initializeropt constructor-initializer: : base ( argument-listopt ) : this ( argument-listopt )
It's saying I can only have one of those.
QUESTION: is 10.11 implying that there's no reason to need to call both or is it simply implying that the language only supports calling one?
Prerequisite: Constructors in C# A user can implement constructor overloading by defining two or more constructors in a class sharing the same name. C# can distinguish the constructors with different signatures. i.e. the constructor must have the same name but with different parameters list.
To call one constructor from another within the same class (for the same object instance), C# uses a colon followed by the this keyword, followed by the parameter list on the callee constructor's declaration. In this case, the constructor that takes all three parameters calls the constructor that takes two parameters.
base (C# Reference) The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class.
Using your example, the answer is: YES. The base constructor will be called for you and you do not need to add one. You are only REQUIRED to use "base(...)" calls in your derived class if you added a constructor with parameters to your Base Class, and didn't add an explicit default constructor.
There is no need to call both, because this
redirects to another constructor that will call base
.
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