C#C
C#2y ago
Mek

✅ Which is the more correct way of class instantiation?

// app.axaml.cs
public override void OnFrameworkInitializationCompleted()
{
    if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
    {
        Helpers hp = new();

        desktop.MainWindow = new MainWindow
        {
            DataContext = new MainWindowViewModel(hp),
        };
    }

    base.OnFrameworkInitializationCompleted();
}

// MainWindowViewModel.cs
public class MainWindowViewModel : ViewModelBase
{
  private Helpers _hp = new();

  // this part is 100% optional. You can use helpers as _hp as well
  public Helpers Hp
  {
      get => _hp;
      set => this.RaiseAndSetIfChanged(ref _hp, value);
  }
}
Is it better to instantiate your used objects like this in the app.axaml.cs file and then pass them off to the main window view model like the public override function at the top or is it better to instantiate your used objects in the main window view model like the code block underneath it? I ask because I've noticed that when I build a new view model, if I instantiate the items I need right there in the class as new instances of that item, I don't have the need for two constructors like
public MainWindowViewModel()
{
    Text = "Hello World!";
}
public MainWindowViewModel(Helpers hp)
{
    _hp = hp;
}
so I'm just curious to if it's user preference, or which is more correct
Was this page helpful?