I’m trying to figure out what is the difference between:
public partial class TestWindow : Window
{
object obj = new object();
public TestWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
and:
public partial class TestWindow : Window
{
object obj;
public TestWindow()
{
InitializeComponent();
obj = new object();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
and:
public partial class TestWindow : Window
{
object obj;
public TestWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
obj = new object();
}
}
it looks like they all act the same and i wonder if there’s any important difference between them, or is it just a “best practice” thing to choose one of them.
Thanks in advance
The answer to your question is you should initialize variables before you use them.
Field initializers run before constructors, and constructors run before any other method, such as your Window_Loaded. It matters because if you try to use your object before it is initialized, you will get a NullReferenceException. If you don’t use your object before Window_Loaded is called, then it makes no difference.