Daniel said:
Hello,
I am coming from Delphi and when I have a method in the inherited class,
I call Inherited to call the base class method.
This is handy cause you can control where and when these things happen.
Can you do this in C#?
Not exactly as you've shown it, no. You can call the base constructor
from the derived constructor, but only as part of the declaration of the
constructor itself. So you can't execute arbitrary code in the
derived constructor and then call the base constructor.
However, that's not to say that there's no way to accomplish what you're
doing. One alternative that should work the same:
public partial class BaseForm : Form
{
public bool isMainForm;
public BaseForm() : this(false)
{
}
public BaseForm(bool initIsMainForm)
{
isMainForm = initIsMainForm;
InitializeComponent();
if (isMainForm)
BaseLibrary.BaseDM = new BaseDataModule();
}
}
public partial class MainForm : BaseForm
{
public MainForm() : base(true)
{
InitializeComponent();
}
}
If you have more complex logic you're trying to encapsulate, the usual
approach would be to create a private initialization method which is
called by any constructor at the appropriate time. That would allow for
more complex logic than just simple calculations and initializations.
Though, now that I think about it, since you can put any expression into
the parameter for the "base" or "this" references, I suspect you could
do just about anything you wanted if you created an evaluated anonymous
method as the parameter for the "base" or "this" reference. At least,
I'm having a hard time coming up with an example of something you
_couldn't_ do that way.
As a really simple example of how to complicate the above, for example:
public partial class BaseForm : Form
{
public bool isMainForm;
public BaseForm() : this(false)
{
}
public BaseForm(bool initIsMainForm)
{
isMainForm = initIsMainForm;
InitializeComponent();
if (isMainForm)
BaseLibrary.BaseDM = new BaseDataModule();
}
}
public partial class MainForm : BaseForm
{
public MainForm() : base((bool delegate() { return true; })())
{
InitializeComponent();
}
}
I didn't actually compile that to confirm that the syntax is allowed,
but assuming it is, then as long as you have a base constructor that
takes a parameter and you can create an anonymous method that returns a
value of the same type, then you'd put that anonymous method there an
evaluate it immediately as the parameter value. The code in the method
would execute prior to calling the base method.
Obviously there'd be no need to do that for the specific example you
started with, but if you had something more complex, like you want to
initialize the value based on some complicated logic that isn't a
simple, single expression, you could do something like the above.
Again, that assumes the compiler accepts the syntax. I'm not sure why
it wouldn't, but I've never tried it and I might be just talking out of
my hat here.
Pete