Hey guys how are you?
I wanted to share you with nice dillema that was raised by one of our team leaders, called: Boaz Davidoff.He encountered with a situation that he wanted to create new instance of an object that inherits from a parent object (which is no problem right...?), BUT firstly he wanted to initiate some members in the child object before of creating the parent object and just after it to call the parent object constructor.
It turns out that this situation is quite impossible in .NET, because by default, you must call the base ctor firstly and just after it to do your stuff, for an example:
public class A{ int a1, a2; public A(int a1, int a2) { this.a1 = a1; this.a2 = a2; // Do your stuff }}public class B : A{ public B(int b1, int b2) : base(b1, b2) { // Do your stuff }}
I wanted here, by calling B ctor, to make some manipulations over b1 and b2 (before calling the base ctor), but encountered with a PROBLEM.
So, take a look on this solution:
public static B CreateBObject(int c1, int c2){ // Do some manipulation over c1 and c2 return new B(c1, c2);}private B(int b1, int b2) : base(b1, b2) { // Do the rest of your stuff}
Some explanations:I created again B ctor, which the only different from the other B ctor is by that it is private (in other words: this object cannot be initialize from outside this class). Now, the addition... I added a static method called CreateBObject, which receives the same params, does some manipulation over them, after it calls the B's private ctor and returns B object like we wanted in the first time.
Nice, huhh? I would like to have some comments
p.s.Thanks Boaz
Remember Me
Page rendered at 11/21/2008 4:56:58 PM (Jerusalem Standard Time, UTC+02:00) Theme Design by Aaron Yuen
Powered by: newtelligence dasBlog 1.8.5223.2
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2008, Eran Nachum
E-mail