I'm playing a little bit with some C# Winforms
/WPF
code and just stumbled upon something strange.
Let's say I have a code like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DoSomething();
// something more if everything worked okay
}
}
What puzzles me is that I cannot simply close the application from the method DoSomething
before the constructor finishes its job. If anything during the execution of DoSomething
fails, I need to close the application immediately; however, it just keeps running, executes the part // something more...
and THEN closes, but that's way too late for me.
I have to put the code for closing the form inside the constructor itself with a following return;
and then it works, but I don't really find that an acceptable solution. I'm trying to move such validation logic from the constructor to my methods.
I've tried things like:
public void DoSomething()
{
Close();
}
and
public void DoSomething()
{
Application.Current.Shutdown();
}
But it doesn't seem to work. Yes, both codes do close the application, but only after a fully finished constructor code.
Why would I need such a thing? Well, because at startup I need to check for various things, like availability of the connection and hardware, validate the user etc, and if anything fails, there's no point of executing more code.
I tried the same principle with Winforms
and WPF
(hence the tags) — works the same way.
Can anybody provide an explanation or a solution?