4

I have the following code:

public string GetSetting(string setting)
{
   return db2.ExecuteScalar<string>("SELECT VALUE FROM Setting WHERE  SettingType = ?", setting);
}

public enum NOA
{
    All = 0,
    Five = 5,
    Seven = 7,
    Nine = 9,
    Ten = 10
}
public static partial class Extensions
{
    public static string Text(this NOA noa)
    {
        switch (noa)
        {
            case NOA.Ten: return "10";
            case NOA.Five: return "5";
            case NOA.Seven: return "7";
            case NOA.Nine: return "9";
        }
        return "";
    }
}

What I would like to do is to get the value of noa and cast it to a NOA.

Here's what I have tried. But I get an error saying "String does not contain a definition for Value":

NOA noa = (NOA)App.DB.GetSetting("NumberOfAnswers").Value;

When I try this. I get an error saying "Cannot convert type string to Japanese.NOA:

NOA noa = (NOA)App.DB.GetSetting("NumberOfAnswers");

Can someone tell me how I can get the value and put it into noa?

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

5

Seems like you are getting the output as string from the specified method. and you want it to be converted to enum, Here better option for you is TryParse, which can be used like the following:

NOA noa;
bool conversionResult = Enum.TryParse(App.DB.GetSetting("NumberOfAnswers"), out noa);

By executing this line you will get a boolean value in conversionResult, if its true means the conversion is completed successfully if it is false which means conversion failed, this time you will get the default value of the NOA in noa, Let the return value from App.DB.GetSetting("NumberOfAnswers") be "10" then the value of noa will be Ten and conversionResult will be true

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • un-lucky - I'm in full control of what goes into the Settings so could you maybe also give a suggestion that doesn't include the checking. Thanks. – Alan2 Dec 16 '16 at 06:12
3

Parse the value to you enum type first and then convert it to integer

var result = result.Text(Enum.Parse(typeof(NOA),App.DB.GetSetting("NumberOfAnswers")));
Sateesh Pagolu
  • 9,282
  • 2
  • 30
  • 48