Constructors
-
I am looking at orgainsing a custom constructor in one of my classes so that it calls through to my default constuctor. I understand this is done as follows: Public TestClass() { //Default Constructor } Public TestClass(int testValue) :this() { } The problem is i also want to call a base constructor, so i effectively want : Public TestClass(int testValue) :base(int testValue2) : this() Which is not valid syntax. Is there an easy way of capturing this in C#? Cheers AJ
-
I am looking at orgainsing a custom constructor in one of my classes so that it calls through to my default constuctor. I understand this is done as follows: Public TestClass() { //Default Constructor } Public TestClass(int testValue) :this() { } The problem is i also want to call a base constructor, so i effectively want : Public TestClass(int testValue) :base(int testValue2) : this() Which is not valid syntax. Is there an easy way of capturing this in C#? Cheers AJ
AJ123 wrote:
Is there an easy way of capturing this in C#?
You put the reference to the base on the default constructor. This chains the constructors together. For example:
class Program { static void Main(string\[\] args) { B b = new B(12); } } class A { public A() { Console.WriteLine("I'm in the constructor of A"); } } class B : A { public B() : base() { Console.WriteLine("I'm in the constructor of B"); } public B(int someValue) : this() { Console.WriteLine("I'm in the constructor of B({0})", someValue); } }
The output is
I'm in the constructor of A
I'm in the constructor of B
I'm in the constructor of B(12)ColinMackay.net Scottish Developers are looking for speakers for user group sessions over the next few months. Do you want to know more?
-
AJ123 wrote:
Is there an easy way of capturing this in C#?
You put the reference to the base on the default constructor. This chains the constructors together. For example:
class Program { static void Main(string\[\] args) { B b = new B(12); } } class A { public A() { Console.WriteLine("I'm in the constructor of A"); } } class B : A { public B() : base() { Console.WriteLine("I'm in the constructor of B"); } public B(int someValue) : this() { Console.WriteLine("I'm in the constructor of B({0})", someValue); } }
The output is
I'm in the constructor of A
I'm in the constructor of B
I'm in the constructor of B(12)ColinMackay.net Scottish Developers are looking for speakers for user group sessions over the next few months. Do you want to know more?