nam
nam

Reputation: 23749

Preferred way of accessing variables from WPF App class

In the following code I'm declaring application level static variable and then accessing it from MainWindow.xaml.cs. Should using static variable here be avoided and instead instantiate the App class in the MainWindow.xaml.cs code below first and use the variable there as var app = Application.Current as App; app.myVariable = "Some Value";. I've read at some places (such as here) that generally we should avoid using static variables.

App.xaml.cs:

public partial class App : Application
{
    private static string myVarialbe {get; set;}
    ...........
}

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
  ..........
  private void btnUserUpdate_Click(object sender, RoutedEventArgs e)
  {
    App.myVariable = "Some value";
    ......
  }
}

Upvotes: 0

Views: 2298

Answers (2)

Torben Schramme
Torben Schramme

Reputation: 2140

As an addition to Clemens answer, I prefer it the following way:

public partial class App : Application
{
    public static App Me => ((App) Application.Current);

    public string MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
    public void DoSomething() { }
    ...
}

By that you don't have to write that casting stuff everywhere. You can now simply write code like this:

App.Me.MyProperty1 = "some value";
App.Me.MyProperty2 = 5;
App.Me.DoSomething();

Upvotes: 2

Clemens
Clemens

Reputation: 128062

Since App is not a static class and an instance of that class is already accessible via the static Application.Current property, there is not need to declare any of its properties static.

Instead, declare non-static properties like

public partial class App : Application
{
    public string MyProperty { get; set; }
    ...
}

and access them like this:

((App)Application.Current).MyProperty = "Some value";

As a note, you should avoid using the as operator without checking the result for null, like

var app = Application.Current as App;
app.MyProperty = "Some Value";

because that would result in a NullReferenceException instead of an InvalidCastException, which is what you actually want to get in case the cast operation fails.

In a potential situation where as may validly return null, test for it:

var app = Application.Current as App;
if (app != null)
{
    app.MyProperty = "Some Value";
}

Upvotes: 1

Related Questions