0

I am struggling to understand or see the benefits or difference over one or the other in the following code scenario.

I have a class like this which uses a field of type LoginViewModel _loginViewModel which allows me access to the LoginViewModel's classes fields and methods:

public partial class LoginWindow : Window
    {
        private readonly LoginViewModel _loginViewModel;

        public LoginWindow()
        {
            InitializeComponent();

            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

            _loginViewModel = Resources["LoginViewModel"] as LoginViewModel;
        }

        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            _loginViewModel.LoginCheck(this);
        }

    }

What is the difference or benefit on using the above with the following instead? They both achieve the same results.

public partial class LoginWindow : Window
    {
        private readonly LoginViewModel _loginViewModel = new LoginViewModel();

        public LoginWindow()
        {
            InitializeComponent();

            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

            _loginViewModel = Resources["LoginViewModel"] as LoginViewModel;
        }

        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            _loginViewModel.LoginCheck(this);
        }

    }
extarlife
  • 17
  • 4
  • 3
    no differences, except the second one creates additional instance of `LoginViewModel` and then never uses it as the instance is replaced in the constructor. – Serg May 31 '22 at 20:18
  • 1
    @extarlife I still don't understand what you mean. In neither example will `_loginViewModel` be null after the constructor is finished (unless `Resources["LoginViewModel"]` returns null, but that doesn't seem to be what you're talking about). The second example is just doing needless work. – Kirk Woll May 31 '22 at 20:38
  • My question may not be the best @KirkWoll what I am asking is why do fields that are not instantiated and are of type class I.e LoginViewModel _loginViewModel allow access to the class I.e. LoginViewModel’s methods? Which is why I asked the difference between the two examples. I was always taught unless static you had to instantiate to access another classes methods etc – extarlife May 31 '22 at 20:46
  • 1
    @extarlife but why do you think `_loginViewModel` is not instantiated when you in fact assign it to whatever is stored at `Resources["LoginViewModel"]` at the end of your constructor? I'm unsure what `Resources` is or why it would have your view model instance, but again, that doesn't seem to be the focus of your question? – Kirk Woll May 31 '22 at 20:49
  • 1
    @KirkWoll thanks I understand now the resources are the bindings to the properties in the view model. Thanks for your help – extarlife May 31 '22 at 20:54

0 Answers0