-1

I have this code:

public partial class SettingsPage : ContentPage
{
    public SettingsPage()
    {
        englishSide.GestureRecognizers.Add(new TapGestureRecognizer
        {
           App.Database.UpdateCardFrontSide(true, "English");
           App.Database.UpdateCardFrontSide(false, "Romaji");
           App.Database.UpdateCardFrontSide(false, "Kana");
           App.Database.UpdateCardFrontSide(false, "Kanji");
        })
            });

I want to replace it with something like this:

public partial class SettingsPage : ContentPage
{
    public SettingsPage()
    {
        englishSide.GestureRecognizers.Add(new TapGestureRecognizer
        {
           App.Database.UpdateCardFrontSide(true, 1);
           App.Database.UpdateCardFrontSide(false, 2);
           App.Database.UpdateCardFrontSide(false, 3);
           App.Database.UpdateCardFrontSide(false, 4);
        })
            });

But is there a way that I can make use a reference or something instead of using the numbers: 1,2,3 or 4

What I would like to do is to use something like Lang.English or Lang.Romaji etc.

Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

3

It sounds like you want something like this:

enum Lang
{
    English = 1,
    Romaji = 2,
    Kana = 3,
    Kanji = 4,
}

Ideally, you will also change your UpdateCardFrontSide() method, and anywhere else these "magic values" are used, so that you use the Lang type instead of int.

Even better if you can avoid requiring specific numeric values for the names. Then you can leave out the assignments in the declaration and let the C# compiler generate values for you.

I could swear your question was already asked before, but I've been unable to find an exact duplicate. In the meantime, you can look at the very useful answers to this related question:

What is main use of Enumeration?

Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
0

If you are going to work with a numeric value in your code but you want it to be meaningful you can use an enum:

enum Language 
{
   English = 1,
   Romaji,
   Kana,
   Kanji
}

The default behavior of enum is to increase by 1 each successive enumerator after the enum identifier, which in this case is English. You can learn more about enums in Microsoft docs

In other hand if you are going to use string instead, you can avoid use 'magic string' by creating an static class with static properties

public static class Constants
{
   public static string ErrorMessage => "This is an error message";
}

And later you can use it like this

ThrowPrettyMessage(Constants.ErrorMessage);
William Bello
  • 292
  • 1
  • 3
  • 13