2

Im creating an Windows Phone app and I find myself writing the same MessageBox.Show("Same error message") multiple times. For instance

"Could not connect to server"

This happens when the user do not have internet access.

Is there somewhere I can put it so that I write the text once and fetch the same text all over the place?

I could write a static class, but maybe there is a file for this?

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
Jason94
  • 13,320
  • 37
  • 106
  • 184

3 Answers3

3

Is there somewhere I can put it so that I write the text once and fetch the same text all over the place?

Yes, there is a special kind of file specifically for this, called strings.resx. It lets you write

MessageBox.Show(strings.ServerNotFound);

instead of

MessageBox.Show("Server not found");

The added benefit (in fact, the intended purpose) of using strings.resx is that your application becomes easily localizable (see answer to this question): adding proper translations and setting the current locale is all it would take to change all strings that your application displays to users with their proper local translations.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

If you want it to be multi-lingual in the end I'd go for the Resource.resx file.

If not, you can go for all kinds of solutions:

  • keep the string there where they make most sense, in the class where you use them
  • store them all together in a dedicated class

Like:

class MyClass 
{
    private static string MyString = "blah";
    // other meaningful stuff
}

Or:

public class MyStaticStrings
{
    public static string MyString = "blah1";
    public static string AnotherString = "blah2";
}
bas
  • 13,550
  • 20
  • 69
  • 146
1

You can create a static variable in the App.xaml.cs page in the App class, so that you can access it all over the application.

nkchandra
  • 5,585
  • 2
  • 30
  • 45