jamesmontemagno / SettingsPlugin

Read and Write Settings Plugin for Xamarin and Windows
MIT License
324 stars 80 forks source link

Handling enums #95

Closed tofutim closed 7 years ago

tofutim commented 7 years ago

Bug Information

Version Number of Plugin: 3.0.1 Device Tested On: Mac Simulator Tested On: n/a Version of VS: 7.2 build 583 Version of Xamarin: 3.8.0.26 (Mac) Versions of other things you are using: ?

Steps to reproduce the Behavior

Create an enum, e.g.,

    public enum ScanModes
    {
        Live,
        Highlight,
        Clipboard,
        Off
    }

try to setup Settings

        public static ScanModes ScanMode
        {
            get => AppSettings.GetValueOrDefault(nameof(ScanMode), ScanModes.Off);
            set => AppSettings.AddOrUpdateValue(nameof(ScanMode), value);
        }

Expected Behavior

Since enums are ints... maybe, should it just work?

Actual Behavior

Can't compile

Code snippet

Screenshots

image

image

jamesmontemagno commented 7 years ago

you could cast them as an Int

You should set them to specific number though in your enum so they don't get changed in the future.

tofutim commented 7 years ago

looks like in your WinPhone example you use string and then Enum.Parse it...

jamesmontemagno commented 7 years ago

Yeah, either way would work.

jamesmontemagno commented 7 years ago

I will leave this in the developers hands on how they want to parse it in and out.

tofutim commented 7 years ago

how would you feel about:

    public static class ISettingsExt
    {
        public static TEnum GetEnumValueOrDefault<TEnum>(this ISettings settings, TEnum defaultValue)
            where TEnum : struct
        {
            TEnum result = default(TEnum);
            bool enumParseResult = false;

            var strTarget = settings.GetValueOrDefault(nameof(TEnum), defaultValue.ToString());
            enumParseResult = Enum.TryParse(strTarget, true, out result);
            return result;
        }

        public static bool AddOrUpdateEnumValue<TEnum>(this ISettings settings, TEnum value, string fileName = null)
        {
            return settings.AddOrUpdateValue(nameof(TEnum), value.ToString(), fileName);
        }
    }

which lets me

        public static ScanModes ScanMode
        {
            get => AppSettings.GetEnumValueOrDefault<ScanModes>(ScanModes.Off);
            set => AppSettings.AddOrUpdateEnumValue<ScanModes>(value);
        }

but yeah, enum is fraught with issues... so maybe dev can decide on implementation. Is the more fundamental value the text? or is it the value?