Reputation: 23859
As shown below, I noticed that when you create a UWP
project in VS2019
, it creates a constructor public App(){....}
in the application class App.xaml.cs
of the project. That constructor then can be used to call (for example) methods of a .NET Standard Class Library project in the same solution as shown in the second code block here.
But, as shown below, the application class App.xaml.cs
of WPF
project does not have such a constructor created by default.
Question Can I just manually create a constructor public App(){....}
in the application class App.xaml.cs
of a WPF
project and call a method of a .NET standard class library from there or it may cause an issues later on?
The App.xaml.cs
of UWP
project:
using System;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
......
namespace Test_UWP_Project
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
..........
............
}
The App.xaml.cs
of WPF
project:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Windows;
.....
.....
namespace Test_WPF_Project
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
Upvotes: 0
Views: 348
Reputation: 169320
Can I just manually create a constructor public App(){....} in the application class App.xaml.cs of a WPF project and call a method of a .NET standard class library from there or it may cause an issues later on?
Yes, you can. As mentioned in the docs, if you don't provide a constructor for your class, C# creates one by default that instantiates the object and sets member variables to the default values. So whenever you want some custom initialization logic, you should define your own constructor.
Depending on what you want to do, it may be a better option to override the OnStartup
method of the App
class instead of creating a constructor though:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
//your code here...
}
}
Upvotes: 1
Reputation: 6744
I've never used an application constructor in WPF, but a quick test shows that you can add a constructor to App.xaml.cs
and it will work just like any other class. Alternatively, you could also handle the Application.StartUp
event. I don't know of any reason why you wouldn't be able to call just about anything from these methods.
Upvotes: 1