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,295
  • 4
  • 43
  • 64
Jason94
  • 12,922
  • 36
  • 102
  • 179

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
  • 697,062
  • 78
  • 1,055
  • 1,465
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
  • 12,614
  • 17
  • 59
  • 129
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,589
  • 1
  • 30
  • 44